簡體   English   中英

使用C從文件讀取數據

[英]Reading data from a file with C

我正在嘗試使用C從文件讀取數據。

這是文件(text.txt)的樣子:

element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7

在下面,您可以看到我的代碼:

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

void read_txt(){
    FILE *fp;
    char buf[100];
    size_t bytes_read;

    fp = fopen("text.txt", "a");

    if (fp == NULL) {
        printf("File couldn't be opened properly.");
        exit(1);
    }

    bytes_read = fread(buf, sizeof(buf), 1, fp);

    printf("%zu\n", bytes_read);
    printf("%s\n", buf);

    fclose(fp);
}


int main(void)
{
    read_txt();
    return 0;
}

不幸的是,我得到的只是以下內容:

0
h
Program ended with exit code: 0

為了實現我的目標(讀取並打印文件中的所有數據),使用fread的正確方法是什么?

您對fread使用看起來還fread 但是,您應該使用"r"而不是"a"打開文件。 當您使用"a"打開文件時,流位於文件的末尾而不是開頭。 當然,您必須循環讀取文件,因為文件包含100個以上的字符

fp = fopen("text.txt", "a");
change to
fp = fopen("text.txt", "r");

返回值成功時,fread()和fwrite()返回讀取或寫入的項目數。 該數字等於僅在size為1時傳輸的字節數。如果發生錯誤或到達文件末尾,則返回值為短項計數(或零)。

我不知道是否應該向您指出常見問題解答,但是這個問題經常出現,解決方案幾乎總是采用以下形式:

static const int M = 3; // For example.
int nread = -1;
int a = -1, b = -1, c = -1;

while ( M == ( nread = scanf( "%d %d %d", &a, &b, &c ) ) )
  do_stuff_with( a, b, c );

// Check why the last call failed.
// Was it due to feof(stdin) with 0 == nread, or did something go wrong?

如果沒有,正確的做法通常是使用以下命令讀取二進制格式的塊:

sometype buffer[M];
while ( M == fread( buffer, sizeof(sometype), M, stdin ) )
  do_stuff_with( M, buffer );

請注意,您正在將sizecount參數反轉為fread() ,盡管它可能仍然可以工作。

有時,人們想要做的是使用fgets()而不是 gets() !)讀取一行,然后使用sscanf()對其進行解析。

太復雜的東西可能需要一個正則表達式庫或解析器。

暫無
暫無

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

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