Read/Write text file in C programming

后端 未结 3 850
攒了一身酷
攒了一身酷 2021-01-13 17:17

I need to write something into a txt file and read the contents, then print them on the screen. Below is the code I have written, it can create and write contents into file

相关标签:
3条回答
  • 2021-01-13 17:45

    You need to add

    fseek(inFile, 0, SEEK_SET);
    

    before

    while ((c=fgetc(inFile)) != EOF)
         putchar(c);
    

    because the file pointer (not the one used for memory allocation) has moved to the end. To read from the file, you have to bring it to the front with the fseek function.

    0 讨论(0)
  • 2021-01-13 17:53
    char c;
    

    is your first problem. getc and getchar return ints, not a chars. Read the man page carefully and change that local to:

    int c;
    

    You're also not resetting the inFile stream after the writes. Put something like:

    fseek(inFile, 0L, SEEK_SET);
    

    before you start reading from that stream. (See the man page.)

    Lastly, your main signature is not standard. Use:

    int main(void) { ...
    
    0 讨论(0)
  • 2021-01-13 18:01

    You need to seek back to the beginning of the file after you write to it and before you start reading:

    fseek(inFile, 0, SEEK_SET);
    
    0 讨论(0)
提交回复
热议问题