C - reading from stdin with a file? - c

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

Related

Error in reading input from another file to a c program

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

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.

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).

fopen() and command line arguments

I'm trying to write a program that will read the first character in a text file. If I use ./a.out myfile.txt it works as intended but if I use ./a.out <myfile.txt I get Segmentation fault: 11. The reason why I'm trying to include the <is because this what is in the spec of the assignment. The below code is just a simplified example that i've made that has the same issue:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int func(int argc, char **argv){
FILE *fp;
int test = 0;
fp = fopen(argv[1], "r");
fscanf(fp, "%i", &test);
printf( "current file: %s \n", argv[1]);
}
int main(int argc, char **argv){
func(argc, argv);
}
Is there any way I can get it to accept the argument as <myfile.txt?
No, nor should you try. Files redirected this way will appear at stdin and you should use that instead (hint: check argc).
If you want to use a file if specified, but otherwise stdin, use something like:
if (argc > 1)
fp = fopen(argv[1], "r");
else
fp = stdin;
In your command ./a.out <myfile you redirect stdin to myfile. This means reading from stdin is actually reading from myfile. So, in this case your argc == 1, so argv[1] you use to open is NULL (see main spec on its arguments). fopen crashes when uses NULL name.
You may do your utility in another way: always read stdin. When you need file to input do like this: cat myfile | ./a.out. This is very nice approach and worth considering.

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;
}

Resources