逐行读取c文件

时间:2016-08-09 01:28:54

标签: c string file lines

所以,我有一个文件,其中有各种各样的行,例如"游戏:1 Bob(@) - 404"玩家的名字是鲍勃,他的最高分是404,有很多这样的线。基本上我必须阅读每一行,看看谁得分最高并打印他的名字并在c中得分。到目前为止,我有这个:

  FILE *fp;
  char * line = NULL;
  size_t len = 0;
  size_t read;

  fp - fopen("Leaderboard.dat", "r");
  if (fp == NULL) {
  printf("File empty/unable to open");
  }

现在我实际上不确定如何正确地做到这一点..

2 个答案:

答案 0 :(得分:0)

char buffer[100];
char code[4];
char name[100];
int maxScore=0;
char maxName[100];
char maxCode[4];

while(fscanf(fp,"%s %s %s %c %d",buffer,name,code,buffer[0],&score) !=EOF)
{
    if(score>maxScore)
    {
        maxScore=score;
        strcpy(maxCode,code);
        strcpy(maxName,name);
    }
}
printf("Name: %s. Code %s Score %d",maxName,maxCode,maxScore);

答案 1 :(得分:-1)

这段代码可以解决问题, 请注意,它尚未经过检查或编译。

   FILE *fp;

   fp = fopen("Leaderboard.dat", "r");

   if (fp == NULL) {
       printf("File empty/unable to open");
   }

    char buffer[100];
    char name[100];
    char winnerName[100];
    char code;
   char winnerCode;
    int maxScore = 0;

    while(fgets(buffer,1000,fp)!=NULL)
    {
        // getting the points from the end of the line
        int last = strlen(buffer) -1;
        while(isdigit(buffer[last]))
        {
            last--;
        }
        int score = atoi(buffer+last+1);

       //getting the name from the start of the line
        int i = 0;
        while(!isdigit(buffer[i]))
        {
            i++;
        }
        i ++;
        int k=0;
        while(!isdigit(buffer[i]))
       {
           if(isalpha(buffer[i]))
           {
                name[k++] = buffer[i];
            }
           if(buffer[i] == '(' )
           {
               code= buffer[i+1];
           }
           i++;
        }
        name[k] = '\0';
        // is greater then max
        if(score > maxScore)
        {
             strcpy(winnerName,name);
             maxScore = score;            
             winnerCode=code;
        }
    }

   printf("Name: %s , Code: %c, Score: %d",winnerName,winnerCode,maxScore);