Reading / writing a text file in C programming

I need to write something to a txt file and read the contents, and then print them on the screen. Below is the code I wrote, it can correctly create and write contents to a file, but it cannot read from a file and print correctly.

#include<stdio.h> #include<stdlib.h> main() { char filename[20]={"c:\\test.txt"}; FILE *inFile; char c; inFile=fopen(filename,"w+"); if(inFile==NULL) { printf("An error occoured!"); exit(1); } while((c=getchar())!=EOF) fputc(c,inFile); fputc('\0',inFile); while((c=fgetc(inFile))!=EOF) putchar(c); } 

Someone will tell me what happened to this program, especially the last two lines. Thank you in advance.

+4
source share
3 answers

You need to add

 fseek(inFile, 0, SEEK_SET); 

before

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

because the file pointer (and not the one used to allocate memory) has moved to the end. To read from a file, you must bring it to the front using the fseek function.

+7
source

You need to return to the beginning of the file after writing it and before you start reading:

 fseek(inFile, 0, SEEK_SET); 
+1
source
 char c; 

- your first problem. getc and getchar return int s, not char s. Read the manual page carefully and change it to:

 int c; 

You also do not flush the inFile stream after recording. Put something like:

 fseek(inFile, 0L, SEEK_SET); 

before you start reading from this thread. (See the man page.)

Finally, your primary signature is not standard. Using:

 int main(void) { ... 
+1
source

Source: https://habr.com/ru/post/1386907/


All Articles