簡體   English   中英

在 C 中將數組寫入文件

[英]Writing an array to a file in C

我試圖將前 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 *, ...)
     ^

許多谷歌搜索都沒有結果。 任何幫助將非常感激。

在允許使用 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

您必須使用打開文件時獲得的FILE *

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

錯誤消息指出fprintf函數需要一個FILE * ,而不是一個char * (或者,同樣的,一個char[] )。

對。 當您調用 fprintf 時,C 編譯器看到的所有內容都是字符串文字(一個char* ),它並非旨在推斷字符串是指文件名。 這就是 fopen 的用途; 它為您提供了一種特殊類型的指針,指示打開的文件。 請注意,您的代碼在打開文件后實際上不會對 fp 執行任何操作,除了關閉它。 所以你只需要在調用 fprintf 時用fp in 替換filename

  1. 應該檢查 fopen 的返回值。

  2. 應該:

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

  3. 應該將 fclose 移出外部 for 循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM