计算文本文件中的帐户数量C.

时间:2014-06-06 13:09:59

标签: c file text

我想计算一个文本文件中的帐号数量,但由于某种原因,我的帐号数量不正确。

帐户的结构如下:

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

1 个答案:

答案 0 :(得分:1)

你正在使用 fscanf 而没有阅读最后一个EOL,因此有一个转变,你的算法不起作用。

我更喜欢使用 fgets ,然后扫描已读取的字符串 - 至少文件指针是准确的,因为整行(除非有超过100个字符)已被读取。< / p>

替换

fscanf(fp,"%i",&tmpAccType);

fgets(dump, 100, fp);
sscanf(dump,"%i",&tmpAccType);

然后在循环的开头

while(!feof(fp)) {

feof 不会返回1,因为尚未读取下一个(空)行。
(见this other answer
您可以用

替换该行
while(fgets(dump, 100, fp)) {

并删除后的下一个fgets(dump, 100, fp),而已经读取了

这就是说程序依赖于一个完美的输入文件 - 您还可以检查程序中的 fgets 返回值(应该 not NULL )(< em> while 在开始时执行一次),如果其中一个错误 NULL ,则退出(带错误)。