[英]FILE IO Trouble
我遇到了一些文件 IO 的问题。
我有这个文件:
数据库数据:
Ryan
12 69.00 30.00 0.00
Bindy Lee
25 120.00 89.00 1.00
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RECORDS 30
#define LEN 20
main()
{
FILE *fptr;
fptr = fopen("db.dat", "r");
int i;
int counter = 2;
for (i = 0; i < counter; i++)
{
char temp1[LEN];
char temp2[LEN + 10];
fgets(temp1, LEN, fptr);
fgets(temp2, LEN, fptr);
printf("%s %s", temp1, temp2);
}
fclose(fptr);
}
我应该得到两条线,但我得到的是这个:
Ryan
12 69.00 30.00 0.00
Bindy Lee
有人可以帮忙吗,我不知道为什么我没有两条线。 以及为什么我得到空间。 很奇怪...谢谢!!!!
fgets
在读取LEN
个字符或到达行尾后停止。 我认为你的问题是你让LEN
太小了。
将您的 printf 更改为更详细的内容,例如printf("temp1='%s'\ntemp2='%s'\n", temp1, temp2);
您应该能够看到实际读入每个字符串的内容。
对于额外的" "
:
改变:
printf("%s %s", temp1, temp2);
至
printf("%s%s", temp1, temp2);
由于字符串已经包含'\n'
。
参考:
A newline character makes fgets stop reading, but it is considered a valid
character and therefore it is included in the string copied to str.
您只读取 40 个字节。 如果你增加 LEN 你可以阅读剩余的行,
或者不是按字节数读取,您可以读取整行直到有新行
#include <string.h>
#define RECORDS 30
#define LEN 20
main()
{
FILE *fptr;
fptr = fopen("b.db", "r");
int i;
int counter = 4;
for (i = 0; i < counter; i++)
{
char temp1[LEN];
fscanf(fptr, "%[^\n]%*c", temp1);
printf("%s\n", temp1);
}
fclose(fptr);
}
如果您有兴趣同时阅读姓名和他的相应记录,您可以调整以下内容,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RECORDS 30
#define LEN 20
main()
{
FILE *fptr;
fptr = fopen("b.db", "r");
int i;
int counter = 2;
for (i = 0; i < counter; i++)
{
char temp1[LEN];
char temp2[RECORDS];
fscanf(fptr, "%[^\n]%*c%[^\n]%*c", temp1, temp2);
printf("%s ---- %s\n", temp1, temp2);
}
fclose(fptr);
}
鉴于您正在接受结构化输入,您可能会考虑使用 scanf 而不是 fgets。 我不清楚你在说什么“我应该得到两条线”。
应该为此更好地工作的代码将类似于:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RECORDS 30
#define LEN 20
main()
{
FILE *fptr;
fptr = fopen("db.dat", "r");
int i;
int counter = 3;
for (i = 0; i < counter; i++)
{
char temp1[LEN];
char temp2[LEN + 10];
fgets(temp1, LEN, fptr);
fgets(temp2, LEN, fptr);
printf("%s%s", temp1, temp2);
}
fclose(fptr);
}
最重要的是您没有阅读最后一行,并且您不需要 printf 语句中的“%s %s”之间的空格。 “%s%s”应该可以正常工作。
我试了一下,调试一下; 我发现问题就像missingno所说的那样:“fgets在读取LEN字符或到达行尾后停止。我认为你的问题是你让LEN太小了。”
第一次 (count = 0),temp2 没有得到 '\n'; 第二次(count = 0),temp1 得到 '\n'; 这就是为什么,您可以尝试调试您的代码.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.