我正在使用Dev-C ++ IDE,现在我正在尝试进行文件处理。这是我的代码:
int main(){
FILE *fp;
int b = 10;
int f;
fp = fopen("data.txt", "w");
//checking if the file exist
if(fp == NULL){
printf("File does not exist,please check!\n");
}else{
printf("we are connected to the file!\n");
}
fprintf (fp, " %d ", b) ;
fclose(fp);
printf("Reading from the file \n");
FILE *fr;
fr=fopen("data.txt","r");
fscanf (fr, " %d ", &f) ;
fclose(fr);
printf("the data from the file %d \n", f);
return 0;
}
这段代码在NetBeans中有效,但是在Dev-C ++中,我只是得到“我们已连接到文件”的消息,但没有将“ 10”的值放入文件中。请您知道答案,让我知道,我该怎么办?
最佳答案
我看不到您的代码有什么问题,但是这里有一些提示
一个好习惯是创建函数并调用这些函数,而不是使用所有内联函数,例如
#define FILENAME "data.txt"
void writeFile()
{
FILE *fp;
int b = 10;
fp = fopen(FILENAME, "w");
//checking if the file exist
if (fp == NULL)
{
perror("File could not be opened for writing\n");
}
else
{
printf("File created\n");
}
fprintf (fp, " %d ", b) ;
fclose(fp);
}
void readFile()
{
int f;
printf("Reading from the file \n");
FILE *fr;
fr=fopen(FILENAME,"r");
fscanf (fr, " %d ", &f) ;
fclose(fr);
printf("the data from the file %d \n", f);
}
int main()
{
writeFile();
readFile();
}
然后从文件读取时,我建议您改用fgets
因为fscanf有导致内存覆盖的趋势,所以使用起来更安全
如果值是意外的。
<- fscanf(fp," %d ", &f );
-> char buf[16]; // some buffer
-> fgets( fp, buf, 10 ); // read as string
-> f = atoi(buf); // convert to int
关于c - Dev-C++文件处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4232295/