簡體   English   中英

從C中的文件讀取基元

[英]reading primitives from file in C

我是C語言的新手,想從文件中讀取一些數據。

實際上,我發現了許多讀取功能,例如fgetc,fgets等。但是我不知道哪種格式最適合讀取以下格式的文件:

0 1500 100.50
1 200     9
2 150     10

我只需要將上面的每一行保存到具有三個數據成員的結構中。

我只需要知道執行此操作的最佳實踐,因此對於C編程我還是陌生的。

謝謝。

嘗試使用fgets閱讀每一行。 每行都可以使用sscanf

FILE* f = fopen("filename.txt", "r");
if (f) { 
    char linebuff[1024];
    char* line = fgets(linebuff, 1024, f);
    while (line != NULL) {
        int first, second;
        float third;
        if (sscanf(line, "%d %d %g", &first, &second, &third) == 3) {
            // do something with them.. 
        } else {
            // handle the case where it was not matched.
        }
        line = fgets(linebuff, 1024, f);
    }
    fclose(f);
}

這可能會有錯誤,但這只是為了給您一個示例,說明如何使用這些函數。 確保驗證sscanf返回了什么。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void
read_file(const char *fname)
{
    FILE *f;
    char line[1024];
    int lineno, int1, int2, nbytes;
    double dbl;


    if ((f = fopen(fname, "r")) == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    for (lineno = 1; fgets(line, sizeof line, f) != NULL; lineno++) {

        int fields = sscanf(line, " %d %d %lg %n", &int1, &int2, &dbl, &nbytes);
        if (fields != 3 || (size_t) nbytes != strlen(line)) {
            fprintf(stderr, "E: %s:%d: badly formatted data\n", fname, lineno);
            exit(EXIT_FAILURE);
        }

        /* do something with the numbers */
        fprintf(stdout, "number one is %d, number two is %d, number three is %f\n", int1, int2, dbl);
    }

    if (fclose(f) == EOF) {
        perror("fclose");
        exit(EXIT_FAILURE);
    }
}

int main(void)
{
        read_file("filename.txt");
        return 0;
}

有關代碼的一些說明:

  • fscanf函數很難使用。 我不得不嘗試一段時間,直到正確為止。 必須使用%d%lg之間的空格字符,以便跳過數字之間的任何空格。 這在必須讀取換行符的行尾特別重要。
  • 大多數代碼都與徹底檢查錯誤有關。 檢查函數調用的幾乎每個返回值是否成功。 另外,將字段數和已讀取的字符數與期望值進行比較。
  • fscanffprintf的格式字符串在細節上有所不同。 請務必閱讀它們的文檔。
  • 我使用fgets的組合一次讀取一行,並使用sscanf解析字段。 我這樣做是因為使用fscanf匹配單個\\n似乎是不可能的。
  • 我將GNU C編譯器與標准警告標志-Wall -Wextra 這有助於避免一些簡單的錯誤。

更新:我忘了檢查一下fgets每次調用是否都准確地讀取了一行。 可能有些行太長而無法放入緩沖區。 應該檢查該行始終以\\n結尾。

暫無
暫無

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

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