Perhaps I understood your need correctly.
I do not correct my code, but I write it myself.
The following is a simple code that is read from the console: code: main.c
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]){ if(argc!=2){ printf("\n wrong number of argument\n"); exit(1); } int numofwords = atoi(argv[1]); char buffer[128]; //printf("%d\n",numofwords); while(numofwords--){ scanf("%s",buffer); printf("%s\n",buffer); } return 0; }
How it works:
~$ gcc main.c -o main
execute:
:~$ ./main wrong number of argument :~$ ./main 2 grijesh grijesh yourname yourname :~$
I hope he understood him. the program simply reads (scan) from the console and displays on the console. The while loop works for the amount of time you pass on command line input.
Now, the text file dumy.txt input file:
:~$ cat dumy.txt yourname myname hisname hername :~$
Now look at what you want to achieve through the code:
:~$ cat dumy.txt | ./main 2 yourname myname :~$
If you want to go through echo :
:~$ echo $'one\ntwo\nthree' | ./main 2 one two :~$
Do you want this?
If yes:
What you missed realized that:
[your code]
(error 1,2)
Your fsacnf is wrong in two ways:
fscanf(argv[1],"%s",&word);
The first argument argv[1] is char* , which is incorrect, you need to pass the type FILE* . As Mr. Oli Charlesworth explained.
Secondly, you still need to read with stdin . Operator | redirects output from the first command to the second command.
(error 3, 4, 5, 6)
By sending the echo "blabla" you just send a single sting, you need to do something like what I did (I added \ n to the echo line for a new line, and my echo line starts with $ so that it does not print like a raw string). an echo so you can read the code on the second argument, which argv[1] not argv[2] . So in your code the next line is incorrect.
int numofwords = atoi(argv[2]);
I fixed this line in my code.
and i initialized to zero i = 0 , while the loop condition is <= , I think it should be < .
(error 7)
The way you run your code is incorrect echo "blabla" | myprog 2 echo "blabla" | myprog 2 your program does not know how mygrog you need to go the full way. as I did ./main , ./ means the current directory.
this is just my opinion about your question. Read also the answer in the comment given by Mr. William Pursel.
Let me know if you have any other doubts.