Thread: Iterating over a txt file in a good old C.

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    1

    Lightbulb Iterating over a txt file in a good old C.

    Hey folks, I know some core theory and the very basics of C, but I cant get my simple program to work, I must have forgot something:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        FILE *ftr = fopen("_TEST.txt", "r");
        if (ftr == NULL) { printf("Can't open the file.\n");return 1;};
    
        char c;
        while ((c=fgetc(ftr) != EOF))
        {
            fscanf(ftr, "%s", &c);
            printf("%c", c);
    
        }
    
        return 0;
    
    }
    I have tried some other output methods but It never prints entire file as I wanted to, in example this one prints nothing.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    959
    Code:
    #include <stdio.h>
    #include <stdlib.h> // you're not actually using anything from here
      
    int main()
    {
        FILE *ftr = fopen("_TEST.txt", "r");
        if (!ftr)
        {
            printf("Can't open the file.\n");
            return 1;
        }
     
        int c; // c should actually be an int (fgetc returns an int, not char)
        while ((c = fgetc(ftr)) != EOF) // parentheses need to be in the right place
        {
            // fgetc already read the char, so you don't need fscanf here
            printf("%c", c);
        }
     
        fclose(ftr); // it's best to explicitly close the file
     
        return 0; 
    }
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with iterating the menu !
    By thebenman in forum C Programming
    Replies: 4
    Last Post: 10-21-2014, 08:06 PM
  2. Replies: 22
    Last Post: 07-31-2013, 08:56 AM
  3. Iterating over multi map
    By coderplus in forum C++ Programming
    Replies: 9
    Last Post: 09-26-2012, 05:55 AM
  4. iterating through hex numbers in c
    By f.g in forum C Programming
    Replies: 18
    Last Post: 08-24-2011, 06:35 PM
  5. Iterating through an array
    By MikeyIckey in forum C Programming
    Replies: 15
    Last Post: 11-10-2007, 10:26 PM

Tags for this Thread