Home > Software engineering >  C fscanf to read each word from a file not working
C fscanf to read each word from a file not working

Time:03-18

I already know how read word by word from a file (using fgets then strok each other), however itd like to find the simplest way and from what Ive seen fscanf, should work.

If fscanf will allocate the pointer of a word inside array[i], why is it not storing anything.

Natural Reader is
john make tame
michael george meier
Bonus Second pass

Im expecting

word = Natural
word = reader
word = is
word = john
...
word = pass
int main(int argc, char *argv[]) {
   FILE *file = fopen(argv[1], "r");
   int ch;
   int count = 0;
   while ((ch = fgetc(file)) != EOF){
      if (ch == '\n' || ch == ' ')
         count  ;
   }
   fseek(file, 0, SEEK_END);
   size_t size = ftell(file);
   fseek(file, 0, SEEK_SET);
   char** words = calloc(count, size * sizeof(char*)  1 );
   int i = 0;
   int x = 0;
   char ligne [80];

   while(fscanf(file, "%s", words[i]) != EOF ){ //or != 1
      printf("%s\n", words[i]);
      i  ;
   }

   free(words);
   fclose(file);
   return 0;
}

CodePudding user response:

If you want to to read a file to the end word by word and only print the words, you don't need all that, you can use only fscanf:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    
    if(argc > 1){

        FILE* file = fopen(argv[1], "r"); 
        
        if(file == NULL){
            return EXIT_FAILURE;       
        }

        char word[100];
    
        while(fscanf(file, "           
  • Related