[英]Counting number of accounts in a text file C
我想计算一个文本文件中的帐户数,但是由于某些原因,我总是得到错误的帐户数。
帐户在文本文件中的结构如下:
accountName
accountPassword
accountNickname
accountId(this is just the position of the account in the file)
accountType
if the account type is 1 (as opposed to 2) there is also:
0
0
0
0
0
因此,其中包含一些帐户的文本文件示例可能如下所示:
bob1
password1
bobby
1
1
0
0
0
0
0
tony1
password1
tony
2
2
mary1
password1
mary
3
2
dave1
password1
dave
4
1
0
0
0
0
0
这是我的代码,用于查找文本文件中有多少个帐户:
userId = 0;
while(!feof(fp))
{
fgets(dump,100, fp);
fgets(dump,100, fp);
fgets(dump,100, fp);
fgets(dump,100, fp);
fscanf(fp,"%i",&tmpAccType); // fifth line from start of account is always account type
if (tmpAccType == 1) // if the user type is an registered user we must skip more variable lines
{
fgets(dump,100, fp);
fgets(dump,100, fp);
fgets(dump,100, fp);
fgets(dump,100, fp);
fgets(dump,100, fp);
}
userId++; //add one to the account position
}
fclose(fp);
由于某种原因,添加3-5个帐户后,程序将开始返回错误的帐户数量。 如果有人可以帮助我,将不胜感激:D
您正在使用fscanf而不读取上一个EOL,因此发生了偏移,并且算法不起作用。
我更喜欢使用fgets ,然后扫描已读取的字符串-至少文件指针是准确的,因为已读取了整行(除非有超过100个字符)。
更换
fscanf(fp,"%i",&tmpAccType);
同
fgets(dump, 100, fp);
sscanf(dump,"%i",&tmpAccType);
然后在循环的开始
while(!feof(fp)) {
feof将不会返回1,因为尚未读取下一行(空)。
(请参阅其他答案 )
您可以用
while(fgets(dump, 100, fp)) {
并删除自从while读取后的下一个fgets(dump, 100, fp)
。
这就是说程序依赖于一个完美的输入文件-您还可以检查程序中所有位置的fgets返回值(不应为NULL )(开始时执行一次),然后返回(错误)他们错误地为NULL 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.