c编程中fscanf()的问题
Trouble with fscanf() in c programming
我正在尝试读取具有特定格式的名为"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();
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 从fscanf读取输入的问题
- SDL fscanf 函数问题
- c编程中fscanf()的问题