Error in reading input from another file to a c program - c

I had been trying to read input from a file to a c code, but something is going wrong. Program is able to read input but not displaying expected output. Here is my c code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void call_me(char* ptr){
system(ptr);
}
int main(){
char str[10];
read(0,str,100);
call_me(str);
printf("executed");
return 0;
}
When I run above code in terminal as:
./sys
and give /bin/sh as input, it leads me to shell.
But on using :
cat file | ./sys
it only prints executed.
Here content of file is:
/bin/sh

Related

Execute hello.c file by using file handlers in C

I'm trying my luck with C lately and I came across to this question where I'm stuck.
I've a hello.c file
CODE 1
#include<stdio.h>
#include<stdlib.h>
int main(){
printf("Hello World");
return 0;
}
I open this file and display the content using the following C program (CODE 2)
CODE 2
#include<fcntl.h>
#include<stdio.h>
int main() {
FILE *fd;
char ch;
fd = fopen("/home/hello.c","r");
if( fd != NULL ) {
while((ch = getc( fd )) != EOF){
putchar(ch);
}
}
return 0;
}
However, I want the output of this code to be Hello World, i.e output of the hello.c file which is read.
How can that be done?
In order to run a c file, first you need to compile it into machine code then execute it.
To compile it: run gcc source-file -o executable-file
To run, execute: executable-file
In order to to the same things in C, use system() function from <stdlib.h>
const char* tempFile = "./tempfile";
const char* sourceFile = "hello.c";
const char compileCommand[255];
sprintf(compileCommand, "gcc %s -o %s", sourceFile, tempFile);
system(compileCommand);
system(tempFile);
This code hasn't been tested.
Currently, in the second program, you are reading hello.c file. So the output of CODE2 will be the contents of hello.c. i.e. #include<stdio.h>...
For what you need, in CODE1, you need to write the output of the program into a separate file (say a.txt) and then read a.txt in CODE2.
Hope this is a sufficient hint for you to solve further.
Your "CODE 2" would have to invoke a C-compiler to compile "CODE 1" and then run it using system() or a function provided by your operating system.
BTW: It is either int main(void) or int main(int argc, char** argv), NOT int main().
As general solution, you may try also to have a look to a C interpreter, like Cling, and try to include it in your project.

C - reading from stdin with a file?

So I have a text file that I'm using in the same directory as my C program and I'm using MinGW as the compiler. This is my input:
./program "hello" > helloworld.txt
In my program in the main function, I have:
#include <stdio.h>
int main(int argc, char *argv[]) {
char c;
while ((c=getchar()) != EOF) {
printf("test\n");
}
return 0;
}
Nothing is printing. The text file definitely has lines in it. I don't know what's going on. This assignment voids the use of fopen() and all that. It is getchar() and stdin only.
Your command isn't reading from the text file, it's writing to it. If you want to read from it, you need to do this:
./program < helloworld.txt
helloworld.txt:
this
is a
test
Output:
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test

input redirection on CMD

Well, I am learning programming in C, and I got an assignment to get 3 characters from an input text file into 3 variables and then print their ASCII values.
I wrote this code:
#include <stdio.h>
int main()
{
char a,b,c;
printf("Insert 3 characters:\n");
a=getch();
b=getch();
c=getch();
printf("%d, %d, %d",(int)a,(int)b,(int)c);
}
I opened a text file (input.txt) and wrote there: "abc".
I managed to compile the code with the MinGW compiler, and on the CMD window that I opened in the folder of the .exe file, I wrote: "Task.exe <input.txt".
The program ran normally. I mean, it waited for me to input 3 characters.
What have I done wrong in my work?
help me please :)
You are asked to read from an input text file.
Why don't you use fopen to open a file handle, and fgetc to read from it?
You could perhaps use fscanf. Don't forget to use the resulting count.
And of course, you should call fclose. Using perror is useful to handle error cases.
So start your code with something that checks that your program has an argument, then fopen it:
int main(int argc, char**argv) {
if (argc<2) { fprintf(stderr, "missing program argument\n");
exit(EXIT_FAILURE); };
FILE* fil = fopen(argv[1], "r");
if (!fil) { perror(argv[1]); exit(EXIT_FAILURE); };
Then run Task.exe input.txt in your console (no redirection needed!).
You should take the habit of reading the documentation of every function you are using, of testing failure cases, of compiling with all warnings & debug info (gcc -Wall -Wextra -std=c99 -g), and of using the debugger (gdb).

How to display the output of a program both to a file and to the console(stdout)?

Say I have the following program that simply outputs "Hello World":
//DEMO.c
#include<stdio.h>
int main()
{
printf("HELLO World");
}
Now I want to display it both to the screen and to a file output.txt.So I enter the following command in the command prompt(I use CodeBlocks on Windows XP and have configured it to work on command prompt as well):
demo.exe>>output.txt>>stdout
It doesn't work!!! Please tell me how to do it,ie how to output the same thing that I see on my screen(When i run the program),simultaneously to a text file?
You will need to download a tee command for Windows. tee is a UNIX/Linux command that copies the standard input to standard output and also outputs to a file. Then, you can do this:
demo.exe | tee output.txt
Here is one port of tee for Windows.
#include <stdio.h>
#define my_fprintf(fp,...) do{fprintf(fp, __VA_ARGS__);fprintf(stdout, __VA_ARGS__);}while(0)
int main(int argc, char **argv){
FILE *fp;
fp=fopen("output.txt","w");//or filename from argv[1]
my_fprintf(fp, "hello world by %s\n", argv[0]);
fclose(fp);
return 0;
}

How to use System(const char*) in TC++

Today , When i coding, met a question..my Code as follow:
#include<stdlib.h>
void main()
{
system("dir");
getch();
}
The question : The user Screen is nothing..Why ? where is my result?
If you want the output when using system, at least into something you can read in your application, you need to pipe the output:
system("dir > /tmp/output.txt");
FILE *f = fopen("/tmp/output.txt", "r");
char text[1024]; // max sizeof of 1 kb, any more and I'd consider using `malloc()` instead.
fread(text, 1, 1024, f);
printf("%s\n", text);
fclose(f);
There are some problems in your program, at least one of which has already been mentioned.
void main() should be int main(void).
As I recall, the Windows/DOS getch function is declared in <conio.h>; you should have a #include directive for it. Be aware that both <conio.h> and getch are non-standard.
Since main returns int, you should return an int result.
But none of these problems explain the problem you're seeing.
With these changes:
#include <stdlib.h>
#include <conio.h>
int main(void)
{
system("dir");
getch();
return 0;
}
This should work; it should show a directory listing of whatever directory your program runs in (which is determined by TC; I don't know the details).
It's possible that the program is running in an empty directory, which means the dir command wouldn't show any files, but it should still produce some output.
Try commenting out the system() call and adding a printf call (note the added #include <stdio.h>):
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void)
{
printf("Hello, world\n");
getch();
return 0;
}
This should open a console window, print "Hello, world" in it, and wait for you to type Enter.
If you still don't see any output (either no console window, or a console window with nothing in it), then you have a problem that's not related to the system() call. Most likely the problem has to do with the way you're using Turbo C (I presume that's what "TC" stands for).
The main function in every C program is supposed to return an int you are returning void
Change void to int:
#include<stdlib.h>
int main()
{
system("dir");
getch();
}
When I tested, the dir command ran in my console and printed to standard out.
May be he is the running the program directly in the Turbo C IDE and hence his output is not visible. If he runs the program directly from cmd line it works. I remember you need to run Alt - F5 or some other combination to see the output window in Turbo C++

Resources