【问题标题】:Passing char array to file using for-loop使用for循环将char数组传递给文件
【发布时间】:2019-09-16 18:55:24
【问题描述】:

我只是在学习如何使用文件 IO,我可能大错特错。我需要创建一个城市名称及其人口密度列表并将其写入文件。我能够使用 for 循环在标准输出中正确打印该列表,但无法将其写入文件。就像我在使用 printf 语句时所说的那样,它工作得很好,但是 (fopen, "w") fprintf 不起作用。我哪里错了?

   printf("Create new file name:\n");
   scanf("%s", outfile);

   fp = fopen(outfile, "w");
   for(i=0;i<10;i++){
        fprintf("%s  %.2f\n", veg[i].name, density );
    }



    fclose(fp);

我希望文件中包含城市列表,但我的程序却崩溃了。我收到此错误消息。

“不兼容的指针类型将'char [10]'传递给'FILE *'类型的参数(又名'struct __sFILE *')”

【问题讨论】:

  • fprintf(fp, "...
  • 别忘了检查fopen调用的返回码。您不应该假设文件已打开。
  • 我喜欢stackoverflow!谢谢@KamilCuk
  • if( fp ) { //write to file} else { printf("Failed to open file");}

标签: c string for-loop file-io char


【解决方案1】:

您需要在 fprintf() 调用中指定要写入的文件。 fprintf(outfile,"%s %.2f\n", veg[i].name, density );

这是文档:https://en.cppreference.com/w/c/io/fprintf

无论您的 fopen 是否失败,您还需要返回。

if (fp != NULL)
{
    printf("File created successfully!\n");
}
else {
    printf("Unable to create file.\n");
    exit(EXIT_FAILURE);

}

请注意,如果您使用 Visual Studio,则必须使用 fprintf_s() 而不是必须指定字符串大小的地方。

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 2017-10-12
    • 2012-07-20
    • 2018-11-28
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多