我正在尝试制作一种数据库程序,但在从 C 文本文件中读取整数时遇到了一些问题。
我有以下代码:
#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;
}
当我尝试运行程序时,它输出“index = 16”,我尝试使用 fgets 和 sscanf 但发生了同样的事情。然而,对于字符串,它决定打印出一堆没有意义的字符。
最佳答案
您在未定义行为中看到的内容是因为您将字符串写入文件并尝试扫描文件中不存在的 INDEX = %d
,因为文件指针指向 之后索引 = 3
扫描前您需要快退(fp)
。
fputs("INDEX = 3",fp);
rewind(fp);
if( fscanf(fp, "INDEX = %d",&index) != 1)
printf("Scanning failes\n");
else
printf("INDEX = %d\n",index);
关于C编程-从文本文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415024/