2

我正在尝试以特定格式读取名为“数据”的文件中的一些数据。该文件中的数据为:

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。我的代码有什么问题吗?请帮我!

4

2 回答 2

5

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

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;
    }
    ...
}
于 2013-10-09T02:16:39.433 回答
-1

您应该使用以下内容循环:

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();
于 2013-10-09T02:16:05.517 回答