我的问题是从一个 100 行的文件中读取,每行有 4 个字段(由 4 个空格分隔),如下所示:
0007 0007 NOVO BANCO, SA 银行
0008 0008 BANCO BAI EUROPA, SA Bancos
0010 0010 BANCO BPI, SA 银行
等...
完成此操作后,我必须将其保存在链表中。
我有这个:
struct list{
int code1;
int code2;
char name[100];
char type[100];
struct list *next, *current;
};
int main()
{
FILE *fp1;
struct list iban;
fp1 = fopen("ibanlist.txt", "r");
if(fopen == NULL)
{
printf("Error!");
}
fscanf(fp1, /*what should i do here?*/, iban.code1, iban.code2, iban.name, iban.type);
//should i use fgets and sscanf instead?
fclose(fp1);
return 0;
}
我的问题是如何从带有空格的文件中读取。例如,在第三个字段中,它在“,”之后有一个空格。这也是我第一次使用列表,谁能告诉我如何做?
最佳答案
这使用 strstr
来标记输入字符串。数据中的第一个分隔符只有 3 个空格,其余为 4 个,因此在每种情况下我都查找 3,然后前进到所有连续的空格。
#include <stdio.h>
#include <string.h>
struct list{
int code1;
int code2;
char name[100];
char type[100];
};
int main(void)
{
FILE *fp;
char str [1000];
char *aptr, *bptr, *cptr;
struct list rec;
if ((fp = fopen("file.txt", "rt")) == NULL)
return 1;
while(fgets(str, sizeof str, fp) != NULL) {
// break the input line
aptr = strstr(str, " "); // isolate first field
if(aptr == NULL)
return 1;
*aptr++ = '\0';
while (*aptr == ' ')
aptr++;
bptr = strstr(aptr, " "); // isolate second field
if(bptr == NULL)
return 1;
*bptr++ = '\0';
while (*bptr == ' ')
bptr++;
cptr = strstr(bptr, " "); // isolate third field
if(cptr == NULL)
return 1;
*cptr++ = '\0';
while (*cptr == ' ')
cptr++;
cptr [ strcspn(cptr, "\r\n") ] = 0; // remove trailing newline etc
// extract the data
if(sscanf(str, "%d", &rec.code1) != 1)
return 1;
if(sscanf(aptr, "%d", &rec.code2) != 1)
return 1;
strcpy(rec.name, bptr);
strcpy(rec.type, cptr);
// print the result
printf("%d/%d/%s/%s\n", rec.code1, rec.code2, rec.name, rec.type);
}
fclose(fp);
return 0;
}
程序输出:
7/7/NOVO BANCO, SA/Bancos
8/8/BANCO BAI EUROPA, SA/Bancos
10/10/BANCO BPI, SA/Bancos
关于c - 从文件中逐行读取并保存在列表中 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866751/