C编程——从文本文件中读取数字
C programming - reading numbers from text file
我正在尝试制作一种数据库程序,运行解决从 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
,它不存在于文件中,因为文件指针指向 INDEX = 3
[= 之后14=]
扫描前需要rewind(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 文本文件中读取整数的一些问题。
我有以下代码:
#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
,它不存在于文件中,因为文件指针指向 INDEX = 3
[= 之后14=]
扫描前需要rewind(fp)
。
fputs("INDEX = 3",fp);
rewind(fp);
if( fscanf(fp, "INDEX = %d",&index) != 1)
printf("Scanning failes\n");
else
printf("INDEX = %d\n",index);