I'm trying to make a sort of a database program and ran into a few issues with reading integers from a text file in C.
I have the following code:
#include <stdio.h>
int main(){
int index;
FILE * fp;
if((fp = fopen("read_file.txt","r+")) == NULL){
perror("Cannot open file");
printf("\nCreating new file...");
if((fp = fopen("read_file.txt","w+")) == NULL){
perror("\nCannot create file.. Terminating..");
return -1;
}
}
fputs("INDEX = 3",fp);
fscanf(fp, "INDEX = %d",&index);
printf("index = %d\n",index);
fclose(fp);
return 0;
}
When i try to run the program it outputs "index = 16", i tried using fgets and sscanf but same thing happens. With strings however it decides to print out a bunch of characters that don't make sense.
What you see in undefined behavior because you write a string to the file and try to scan INDEX = %d
which is not there in the file because of the file pointer is pointing after INDEX = 3
You need to rewind(fp)
before scanning.
fputs("INDEX = 3",fp);
rewind(fp);
if( fscanf(fp, "INDEX = %d",&index) != 1)
printf("Scanning failes\n");
else
printf("INDEX = %d\n",index);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.