【问题标题】:Writing an array to a file in C将数组写入C中的文件
【发布时间】:2013-10-27 23:38:34
【问题描述】:

我正在尝试将前 N 个素数的数组写入 txt 文件,每行 5 个条目,每个条目之间有 10 个空格。相关代码如下:

#include<stdio.h>
#include<math.h>

#define N 1000

...

void writePrimesToFile(int p[N], char filename[80])
{
    int i;
    FILE *fp = fopen(filename, "w");
    for(i = 0; i<=N-1; i++)
    {
        for(i = 0; i<5; i++)
        {
            fprintf(filename, "%10%i", p[i]);
        }
        printf("/n");
    fclose(fp);
    }


    printf("Writing array of primes to file.\n");
}

编译器抛出以下错误:

primes.c:40:4: warning: passing argument 1 of ‘fprintf’ from incompatible pointer type [enabled by default]
    fprintf(filename, "%10%i", p[i]);
    ^
In file included from /usr/include/stdio.h:29:0,
                 from primes.c:1:
/usr/include/stdio.h:169:5: note: expected ‘struct FILE *’ but argument is of type ‘char *’
 int _EXFUN(fprintf, (FILE *, const char *, ...)
     ^

许多 Google 搜索都没有结果。任何帮助将不胜感激。

【问题讨论】:

  • 错误信息再清楚不过了:expected ‘struct FILE *’ but argument is of type ‘char *’

标签: c arrays file output


【解决方案1】:

在允许使用 fp 之前测试fopen() 的输出:

FILE *fp = fopen(filename, "w");   
if(fp)//will be null if failed to open
{
    //continue with stuff
    //...    
}

fprintf(...) 的第一个参数也是FILE * 类型。变化:

fprintf(filename, "%10%i", p[i]);
        ^^^^^^^^

fprintf(fp, "%i", p[i]);
        ^^//pointer to FILE struct

【讨论】:

    【解决方案2】:

    您必须使用打开文件时获得的FILE *

       fprintf(fp, "%10%i", p[i]);
    

    错误消息指出fprintf 函数需要FILE *,而不是char *(或者,相同的是char[])。

    【讨论】:

      【解决方案3】:

      没错。当您调用 fprintf 时,C 编译器看到的所有内容都是字符串文字(char*),它并非旨在推断字符串引用文件名。这就是 fopen 的用途;它为您提供了一种特殊类型的指针,指示打开的文件。请注意,您的代码在打开文件后实际上并没有对 fp 做任何事情,除了关闭它。因此,您只需在调用 fprintf 时将 fp 替换为 filename

      【讨论】:

        【解决方案4】:
        1. 应该检查fopen的返回值。

        2. 应该是:

          fprintf(fp, "%10d", p[i]);

        3. 应将 fclose 移出外部 for 循环。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-07
          • 1970-01-01
          • 2010-09-27
          • 1970-01-01
          相关资源
          最近更新 更多