-1

So I'm currently learning file processing for my assignment, and I'm wondering why this code

#include<stdio.h>

int main(){
    char test[255];
    FILE *open;
    open = fopen("data.txt", "r");
    while(fscanf(open, "%s", test)!=EOF){
        printf("%s", test);
    }
}

works while the following one

#include<stdio.h>

int main(){
    char test[255];
    FILE *open;
    open = fopen("data.txt", "r");
    fscanf(open,"%s", test);
    printf("%s", *test);
}

didn't, any answer would be appreciated!

raiyan22
  • 1,043
  • 10
  • 20
Cyanta
  • 1
  • 3

2 Answers2

0

Your second solution does not work because of this line:

printf("%s", *test);

You provide the first character of text[] as parameter, and printf() tries to use it as a pointer for its format "%s". This is Undefined Behavior. Most probably your program crashes at this point.

Remove the dereferencing operator * and it will work in the sense that at most one sequence of non-whitespace characters are output:

printf("%s", test);

the busybee
  • 10,755
  • 3
  • 13
  • 30
-1

On success, the fscanf() function returns the number of values read and on error or end of the file it returns EOF or -1

Now if you do not put this function inside a while loop, it will read one character only. Essentially we want it to run as long as there is data to read inside the text file so we put it inside a while loop, so as long as the file has data to read, it will not return an EOF or a -1 so it will keep on executing and read the data from the file.
For further explanation check fscanf() Function in C

raiyan22
  • 1,043
  • 10
  • 20
  • so the fscanf function only scans 1 character at a time? thats why i need to put it into a loop? – Cyanta Jan 07 '22 at 14:24
  • This is plain wrong. The family of `scanf()` reads as many characters as it sees fit or are available. With the format `"%s"` it will read a sequence of non-whitespace characters. – the busybee Jan 07 '22 at 22:48