I wanted to know how to read data from an unknown source of input, meaning I don’t know if the user is going to just type a sentence or is he going to give me some text file.
I’ve tried using fscanf since I’ve read it is meant for unformatted input type
this is my code, Im suppose to get some type of input(file or just a sentence (echo bla bla bla) and "int" and print only the "int" first words. The program should be used for piping meaning the command would look like that :
There are 2 ways to ways of using the program:
1.echo "blabla" | myprog 2 (number of words to print)
2.cat input.txt | myprog 2 (number of words to print)
The problematic line is line 16, I tried using fscanf
Thanks!
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5
6
7 int main(int argc, char *argv[]){
8 char *words[32];
9 int numofwords = atoi(argv[2]);
10 int i=0;
11 int len;
12 char *word = malloc (32 * sizeof(char));
13 char c;
14 while (i<=numofwords){
15 if ((c = getc (argv[1])) != EOF){
16 fscanf(argv[1],"%s",&word);
17 len = strlen (word);
18 words[i] = malloc ((len+1) * sizeof(char));
19 i++
20 }
21 printf(words[i]);
22 }
23 return 0;
24 }
25
May be I am correctly understood your need.
I am not rectifying your code but writing my own.
Below is simple code that read from console: code:
main.cHow does it works:
execute:
I hope its understood to you. the program simply read (scan) from console and print out to console. The while loop runs for number of time you pass on command line input.
Now, A text file
dumy.txta input file:Now see what you want to achieve through you code:
If you want to pass through
echo:Is this you want?
If yes:
What you miss understood that:
[your code]
(mistake 1,2)
Your fsacnf is wrong in two ways:
First argument is
argv[1]ischar*that is wrong you need to passFILE*type. As explained in Mr. Oli Charlesworth’s answer.Second you still need to read from
stdin.|operator redirects the output from first command to second command.(mistake 3, 4, 5, 6)
By sending
echo "blabla"you are just sending a single sting you need to do something like I did (I added \n in echo string for new line also my echo string start with$so it not print as raw string). echo so that you can read from code according to second argument that isargv[1]notargv[2]. So in your code following line is wrong too.I corrected this line in my code.
and
iis initialised to zeroi = 0, in while loop condition is<=, I think it should be<.(mistake 7)
The way you run your code is wrong
echo "blabla" | myprog 2your program not know asmygrogyou have to pass complete path. like I did./main,./means current directory.this just my view about your question. Read also the answer in comment given by Mr. William Pursell.
Let me know if you have other doubts.