我正在使用Dev-C++集成开发环境,现在我正在尝试创建文件handling.here is my code:
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“的值放入文件中。请你知道答案,让我知道,我该怎么办?
发布于 2010-11-20 19:20:05
我看不出您的代码有任何错误,但这里有一些提示
一个好习惯是创建函数并调用它们,而不是所有的内联函数,例如
#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发布于 2017-12-11 18:49:35
它工作得很完美。IDE的代码没有问题。请将代码移到windows中的“我的文档”中。试试看...我认为这是一个许可问题。
https://stackoverflow.com/questions/4232295
复制相似问题