【发布时间】:2021-12-12 20:50:53
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX (10)
struct parola{
char parola1[MAX+1];
char parola2[MAX+1];
char parola3[MAX+1];
};
struct parola2{
char parola1x[MAX+1];
char parola2x[MAX+1];
char parola3x[MAX+1];
};
struct parola *leggi_file(FILE *fp, int *count){
int dim = 16;
int j;
struct parola *v, *v2;
int conv = 0;
char buf[1024];
if(!(v = malloc(dim *sizeof(*v)))){
free(v);
puts("non va");
}
while(fgets(buf, sizeof(buf), fp) != NULL){
v2 = v + (*count);
conv =
sscanf(buf, "%s %s %s", v->parola1, v->parola2, v->parola3);
printf("\n%s ", v[*count].parola1);
printf("%s ", v[*count].parola2);
printf("%s\n", v[*count].parola3);
if(*count >= dim){
dim *= 2;
if(!(v = realloc(v, sizeof(*v)*dim))){
free(v);
return NULL;
}
(*count)++;
}
}
return v;
}
void visual(struct parola *v, int count){
int i;
for(i=0; i<count; i++){
printf("%s %s %s\n", v[i].parola1,v[i].parola2,v[i].parola3);
}
}
int main(int argc, char *argv[]){
int count= 0;
struct parola *v;
FILE *fp;
fp= fopen(argv[1], "r");
if (fp != 0){
} else{
return 1;
}
if(!(v = leggi_file(fp, &count))){
return 0;
}
visual(v,count);
}
程序应该从 ./a.out "file1.txt" 中读取每行 3 个单词的文件(非强制性),我需要将它保存在结构 "parola" 中。我的问题是我无法以正确的方式做到这一点。 *保存后,我需要处理结构的单个单词,比如修改 ecc。
文件如下: 字 1 字 2 字 3 (\n) 字 4 字 5 (\n) word6 word7 word8 (\n)
但如果我保存,它应该是相同的,但如果我将其可视化,我会收到: 字 1 字 2 字 3 (\n) 字 4 字 5 字 3 (\n) word6 word7 word8 (\n)
【问题讨论】:
-
我推荐你使用你的编辑器重新缩进你的代码,一个问题应该会变得很明显。就像您尝试在调试器中单步执行代码一样。
-
使用
sscanf()的返回值,即conv...conv = sscanf(buf, "%s %s %s", v->parola1, v->parola2, v->parola3); if (conv > 0) printf("\n%s ", v[*count].parola1); if (conv > 1) printf("\n%s ", v[*count].parola2); if (conv > 2) printf("\n%s ", v[*count].parola3); -
您希望输出与
file1.txt中的文本相同吗?为什么不直接打印在EOF之前阅读的内容? -
没有空的 if条件,只做if (fp == NULL) { return 1; } -
如果 malloc失败,则在返回的NULL 指针上调用free是没有意义的,该操作是无操作的。