【发布时间】:2019-07-02 09:58:05
【问题描述】:
我一直在尝试在 C 中进行文件练习,但是当我运行教授或教程中的程序(应该可以)时,文件总是空白。有解决办法吗?
我的电脑很旧了,但它仍然可以运行各种程序,我不明白为什么它不能处理文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*program that prints on a file your shopping list*/
int main(int argc, char **argv)
{
FILE *fp= fopen("Shopping list.txt", "w");
int end= 0; //have you finished writing the articles
char article[80]; //the article you want to buy
int n; //quantity
while(!end){
printf("What do you need to buy? ");
fgets(article, 80, stdin);
article[strlen(article)- 1]= '\0';
fprintf(fp, "%s ", article);
printf("How much of it? ");
scanf("%d", &n);
fprintf(fp, "%d\n", n);
printf("Are you done? (1= Yes, 0= No) ");
scanf("%d%*c", &end);
}
fclose(fp);
}
它应该在您输入的文件(已创建并保持为空)上打印出来。没有错误提示
【问题讨论】:
-
为什么我用输入“abc”、“3”和“1”运行程序,结果是创建了一个名为“Shopping list.txt”的文件,内容为“abc 3”。您应该在程序运行后显示您提供的确切输入和“购物清单.txt”的内容。
-
两个建议: 1) 调用
fopen后检查fp == 0是否意味着由于某种原因无法打开文件。 2) 将相对路径“Shopping list.txt”更改为绝对路径,例如"c:\\temp\\shopping list.txt" 或 "/tmp/shopping_list.txt" 等,以避免混淆代码耗尽一些临时文件夹(我见过很多 VS 用户被欺骗这个) -
scanf和朋友们的返回值千万不要忽略。 -
我敢打赌,你正在使用 IDE。如果为真,则该文件可能已创建并填充,但不在您正在查找的目录中。尝试在整个磁盘中搜索它,或者在
main中添加printf("%s\n", getcwd());作为第一条指令以了解*@!# 文件的位置。 -
我已经解决了这个问题。很简单,在 fopen 期间,我必须指定绝对路径。它已经填满了文件。谢谢大家