[英]create a file in c programming and write hello world in the file
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
我已经尝试过使用此代码在c编程中创建一个文件,并编写文本“ Hello world!”。 在里面。 此代码有什么问题?
如果您想知道哪里出了问题,请检查fopen
的结果
opening = fopen("hello.usr","w");
if (opening == NULL) {
perror("fopen");
}
截至目前,您尚不知道是否设法写入文件,因此,这里有一条建议可以检查该文件。
FILE *opening;
opening = fopen("hello.usr", "w");
if (opening == NULL){
perror("fopen");
return 0;
}
通过在此处返回0,您可以删除分段错误选项,因为即使该文件不存在,该代码仍会尝试写入该文件。
您最肯定会收到的错误消息不是由编译器产生的。 在我看来,它就像是一些自动检查器的消息,用于测试提交的解决方案的正确性。
确保输出与所需的输出完全匹配。
消息:
您的程序的输出比预期的短
可能表示换行符('\\ n')出了问题。 检查那些。
例如,如果所需的输出是:
写入文件成功。 关闭程序。
...打印在一行中,您的输出显然不匹配,因为它在第一句之后有新行。 并且如果检查器测试了换行符的首次出现,它只会看到
写入文件成功。
这可能是许多可能的解释之一。 如果是这种情况,请尝试简单地:
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
// printf("Writing to the file was successful.\n");
// printf("Closing the program");
printf("Writing to the file was successful. Closing the program\n");
return 0;
}
另请注意,此类错误消息(在自动测试环境中)通常是由难以注意到的遗漏,添加的额外或混乱的不可打印字符(空格,制表符,新行)或标点符号触发的。
在这方面,您可能还需要检查打印到文件中的文本。
尝试在fopen中使用“ w”代替“ w”
尝试以下
#include <stdio.h>
int main() {
FILE *opening = fopen("hello.usr", "w");
if(opening == NULL){
printf("An error occurred when opening the file!");
return 0;
}
else{
fprintf(opening, "Hello world!\n");
fclose(opening);
printf("Writing to the file was successful.\nClosing the program.\n");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.