用C编程创建一个文件,在文件中写入“Hello world!

wgeznvg7  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(139)

我已经在我的设备上尝试了这段代码,它创建了一个名为“hello.usr”的文件,并成功地打印了文本“Hello world!”。

#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;
}

字符串
但是我提交这个程序的在线判断给了我一个错误。你的程序的输出比预期的要短
我该如何克服呢?
一条评论说:
编写一个程序,将文本“Hello world!”打印到文件“hello.usr”中。该文件不存在,因此必须创建它。最后,程序必须在屏幕上打印一条消息,表明写入文件成功。打印到文件的文本必须与赋值完全匹配。示例输出:写入文件成功。正在关闭程序。程序的输出必须与示例输出完全相同(最严格的比较级别)。

vuktfyat

vuktfyat1#

我不知道你说的在线判断是什么意思,但是在你写的结尾使用 \n 是一件好事。

#include<stdio.h>    
int main()
{    
    FILE *opening;
    opening = fopen("hello.usr","w");
    fprintf(opening,"Hello world!\n"); // Here    
    fclose(opening);
    printf("Writing to the file was successful. Closing the program");
    return 0;
}

字符串
阅读你的评论,现在,我不认为解决方案是有关 \n 的。
你应该考虑的其他一些好东西是:

  • "," 后添加空格
  • 也许可以加一些空白行,让你自己理解

如果我要写同样的东西,我会这样做:

#include<stdio.h>    

int main() {    
    FILE* file = fopen("hello.usr", "w");
    fprintf(file, "Hello world!");

    fclose(file);
    printf("Writing to the file was successful. Closing the program.");

    return 0;
}

相关问题