簡體   English   中英

C編程中的fscanf()麻煩

[英]Trouble with fscanf() in c programming

我正在嘗試讀取具有特定格式的名為“數據”的文件中的某些數據。 該文件中的數據是:

0 mpi_write() 100
1 mpi_write() 200
2 mpi_write() 300
4 mpi_write() 400
5 mpi_write() 1000

然后代碼如下:

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

typedef struct tracetype{
    int pid;
    char* operation;
    int size;
}tracetyper;

void main(){
    FILE* file1;
    file1=fopen("./data","r");
    if(file1==NULL){
        printf("cannot open file");
        exit(1);
    }else{
        tracetyper* t=(tracetyper*)malloc(sizeof(tracetyper));
        while(feof(file1)!=EOF){
            fscanf(file1,"%d %s %d\n",&t->pid,t->operation,&t->size);

            printf("pid:%d,operation:%s,size:%d",t->pid,t->operation,t->size);
        }
        free(t);
    }
    fclose(file1);
}

使用gdb運行時,我發現fscanf不會將數據寫入t-> pid,t-> operation和t-> size。 我的代碼有什么問題嗎? 請幫我!

您的程序具有未定義的行為:您正在將%s數據讀取到未初始化的char*指針中。 您需要使用malloc分配operation ,或者如果您知道最大長度為20個字符,則可以將其固定的字符串放入struct本身:

typedef struct tracetype{
    int pid;
    char operation[21]; // +1 for null terminator
    int size;
} tracetyper;

讀取%s數據時,應始終告知fscanf長度限制,如下所示:

fscanf(file1,"%d %20s %d\n",&t->pid,t->operation,&t->size);

最后,您應該刪除字符串末尾的\\n ,並檢查返回值的計數,而不是檢查feof ,如下所示:

for (;;) { // Infinite loop
    ...
    if (fscanf(file1,"%d %20s %d",&t->pid,t->operation,&t->size) != 3) {
        break;
    }
    ...
}

您應該使用類似以下內容的循環:

while ( (fscanf(file1,"%d %s %d\n",&t->pid,t->operation,&t->size)) != EOF) {
   printf("pid:%d,operation:%s,size:%d",t->pid,t->operation,t->size);
}

您還需要在結構中為char數組添加malloc。 另外,將t插入為

if (t == NULL)
   cleanup();

暫無
暫無

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

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