c编程中fscanf()的问题

Trouble with fscanf() in c programming

本文关键字:问题 fscanf 编程      更新时间:2023-10-16

我正在尝试读取具有特定格式的名为"data"的文件中的一些数据。此文件中的数据为:

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 %dn",&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-> 操作和 t->size。我的代码有什么问题还是什么?请帮帮我!

您的程序具有未定义的行为:您正在将%s数据读入未初始化的char*指针。您需要使用 malloc 分配operation,或者如果您知道最大长度为 20 个字符,则可以将其固定字符串放入结构本身:

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

读取%s数据时,应始终告诉fscanf长度的限制,如下所示:

fscanf(file1,"%d %20s %dn",&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 %dn",&t->pid,t->operation,&t->size)) != EOF) {
   printf("pid:%d,operation:%s,size:%d",t->pid,t->operation,t->size);
}

您还需要在结构中添加字符数组的 malloc。此外,插入t

if (t == NULL)
   cleanup();