簡體   English   中英

fscanf無法從txt文件讀取數據

[英]fscanf fails to read data from txt file

我正在嘗試使用ubuntu在eclipse上運行我的代碼。

我已經將使用fprintf的數據轉儲到一個txt文件中,並使用fscanf讀取了該文件。 我無法將這些值讀入數據數組。

下面是我的代碼:

#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main(){
    char* data;
    FILE *fp;
    size_t result;
    data = (char*) malloc (sizeof(char)*(1280*800));//Size of one frame
    if (data==NULL){
        printf("NOt able to allocate memory properly\n");
        exit (1);
    }
    fp = fopen ("\\home\\studinstru\\Desktop\\filedump.txt", "r");
    if(fp==NULL){
        printf("Error in creating dump file\n");
        exit (1);
    }
    for(int m = 0;m<1280;m++){
         for(int n = 0;n<800;n++){
         fscanf(fp,"%d/t",data[m*800 + n]);
     }
   }
    fclose(fp);
    return 0;
}

這是我的filedump.txt數據:

79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82
79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82
79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82 ....

你能告訴我這是什么問題嗎?

您的代碼有很多問題

  1. 您的fscanf()格式錯誤,並且您正在傳遞值而不是其地址,則應使用

     fscanf(fp, "%d", &data[n + 800 * m]); 

    如果您的意思是"\\t"tab符,則無論如何都不需要,並且傳遞值而不是地址是Undefined Behavior,因為fscanf()會將值視為指針,並且不太可能指向有效的內存而且,它是未初始化的,這是未定義行為的另一個原因。

  2. 您將data聲明為char *data並在其中存儲int ,這也是Undefined Behavior。

  3. 您必須檢查fscanf()的返回值,因為如果失敗,則該值將未初始化,並且將再次出現“未定義行為”,並且您將要讀取文件的末尾,因為您將永遠不知道是否達到了。

  4. 您正在寫入文件,然后將其打開以進行讀取,這

     fprintf(fp, "\\n"); 

    是錯誤的,您不需要它從文件中讀取。

  5. 盡管在這種情況下這不會引起問題,但是請不要malloc()的結果 ,它將提高代碼的質量。

  6. 不要使用sizeof(char)這會使您的代碼更難閱讀,並且由於標准要求sizeof(char) == 1 ,因此完全沒有必要。

  7. 您不需要嵌套循環即可讀取數據,因為fscanf()忽略所有空白字符,因此數據的形狀無關緊要。

    讀取文件並使用計數器在數組中移動就足夠了,最后,您可以檢查讀取了多少個值以驗證數據的完整性。

這是您的代碼的固定版本

#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main()
{
    FILE  *fp;
    size_t index;
    int   *data;

    data = malloc(1280 * 800);
    if (data == NULL)
    {
        printf("NOt able to allocate memory properly\n");
        return 1;
    }

    fp = fopen("\\home\\studinstru\\Desktop\\filedump.txt", "r");
    if (fp == NULL)
    {
        printf("Error in creating dump file\n");
        free(data);

        return 2;
    }

    while (fscanf(fp, "%d", &data[index]) == 1)
    {
        fprintf(stdout, "%d ", data[index]);
        index += 1;
        if (index % 800 == 0)
            printf("\n");
    }

    fclose(fp);
    return 0;
}

注意 :我建議使用編譯器警告,它們將幫助防止愚蠢的錯誤和其他一些錯誤,例如char *data並將int讀入其中。

另外,從您的文件路徑"\\\\home\\\\studinstru\\\\Desktop\\\\filedump.txt"看來,您使用的是非Windows系統,並且目錄分隔符很可能是/而不是\\ ,因此正確的路徑為成為

"/home/studinstru/Desktop/filedump.txt"

更換

fscanf(fp,"%d/t",data[m*800 + n]);

fscanf(fp,"%d/t",&data[m*800 + n]);

fscanf()需要將目標變量的地址作為參數,而不是變量本身。

另外我不明白為什么要這樣做:

fprintf(fp,"\\n");

暫無
暫無

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

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