简体   繁体   English

在 C 中将数组写入文件

[英]Writing an array to a file in C

I am attempting to write an array of the first N primes to a txt file in rows of 5 entries each, with 10 spaces between each entry.我试图将前 N 个素数的数组写入 txt 文件,每行 5 个条目,每个条目之间有 10 个空格。 The relevant code is as follows:相关代码如下:

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

The compiler throws the following error:编译器抛出以下错误:

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 *, ...)
     ^

Numerous Google searches have not been fruitful.许多谷歌搜索都没有结果。 Any help would be much appreciated.任何帮助将非常感激。

Test the output of fopen() before allowing fp to be used:在允许使用 fp 之前测试fopen()的输出:

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

Also 1st argument to fprintf(...) is of type FILE * . fprintf(...) 的第一个参数也是FILE *类型。 Change:改变:

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

to

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

You must use the FILE * that you obtained when you opened the file.您必须使用打开文件时获得的FILE *

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

The error message states that fprintf function expects a FILE * , not a char * (or, what is the same, a char[] ).错误消息指出fprintf函数需要一个FILE * ,而不是一个char * (或者,同样的,一个char[] )。

Right.对。 All the C compiler sees, when you call fprintf, is a string literal (a char* ) and it is not designed to infer that a string refers to a filename.当您调用 fprintf 时,C 编译器看到的所有内容都是字符串文字(一个char* ),它并非旨在推断字符串是指文件名。 That's what fopen is for;这就是 fopen 的用途; it gives you a special type of pointer that indicates an open file.它为您提供了一种特殊类型的指针,指示打开的文件。 Note that your code doesn't actually do anything with fp after it opens the file, except to close it.请注意,您的代码在打开文件后实际上不会对 fp 执行任何操作,除了关闭它。 So you just need to substitute fp in for filename in your call to fprintf.所以你只需要在调用 fprintf 时用fp in 替换filename

  1. Should check the return value of fopen.应该检查 fopen 的返回值。

  2. Should be:应该:

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

  3. Should move fclose out of the outer for loop.应该将 fclose 移出外部 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM