从fgets和strtok的一个文件的读取和解析行 [英] Reading and parsing lines from a file with fgets and strtok

查看:530
本文介绍了从fgets和strtok的一个文件的读取和解析行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与code的一个相当基本的有点麻烦。我需要阅读从以下所示的文件中的每一行,与strtok的将它分成3份,每个部分存储到一个数组。对于目标和助攻的阵列可以正常使用,但由于某些原因,整个名称数组充满了从文件中读取姓。

I'm having trouble with a fairly basic bit of code. I need to read each line from the file shown below, split it up into the 3 parts with strtok, and store each part into an array. The arrays for "goals" and "assists" are working perfectly, but for some reason the entire name array is filled with the last name read from the file.

输入文件:

Redden 2 0
Berglund 5 2
Jackman 2 0
Stewart 4 0
Oshie 3 5
McDonald 2 4
Pietrangelo 2 7
Perron 2 6
Tarasenko 5 5

相关code:

int main(int argc, char* argv){  
    FILE* inFile = fopen(argv[1],"r");
    char ** nameArray;
    int * goalArray;
    int * assistArray;
    int size = countLinesInFile(inFile);
    allocateMemory(&goalArray, &assistArray, &nameArray, size);
    readLinesFromFile(inFile, goalArray, assistArray, nameArray, size);
}

void allocateMemory(int** goals, int** assists, char*** names, int size)
{
  *goals = malloc(size*sizeof(int));
  *assists = malloc(size*sizeof(int));
  *names = malloc(size*sizeof(char *));
  int i;
  for(i=0; i<size; i++)
  {
    *(*names + i) = calloc(MAX_NAME,sizeof(char));
  }
}

void readLinesFromFile(FILE* fPtr, int* goals, int* assists, char** names, int numLines)
{
  int i;
  char * buffer = malloc(MAX_LINE*sizeof(char));
  for(i = 0; i<numLines; i++)
  {
    if(fgets(buffer, MAX_LINE, fPtr)!= NULL)
    {
      names[i] = strtok(buffer, " \n");
      goals[i] = atoi(strtok(NULL, " \n"));
      assists[i] = atoi(strtok(NULL, " \n"));
    }
  }
}

由于某些原因,nameArray [0-9]中都含有塔拉先科,以及与此任何帮助将大大AP preciated。

For some reason, nameArray[0-9] all contain "Tarasenko", and any help with this would be greatly appreciated.

推荐答案

strtok的 返回一个指向包含下一个令牌的空终止字符串。要真正复制此令牌,你应该使用 的strcpy

strcpy(names[i],    strtok(buffer,      " \n"));
strcpy(goals[i],    atoi(strtok(NULL,   " \n")));
strcpy(assists[i],  atoi(strtok(NULL,   " \n")));

另外请注意,有一个在您code内存泄漏:

Also note that there is a memory leak in your code:

void readLinesFromFile(/*...*/)
{
    char * buffer = malloc(MAX_LINE*sizeof(char));
    // ...
    fgets(buffer, MAX_LINE, fPtr);
    // ...
}

您动态调用的malloc 分配缓存,但你不释放此内存。不要忘记调用 免费() 上的指针指向已被的malloc 分配的内存。但在这种情况下,自动存储持续时间的阵列将是一个较好的选择:

You dynamically allocate the buffer by calling malloc, but you don't free this memory. Don't forget to call free() on a pointer pointing to the memory that has been allocated by malloc. But in this case, the array with automatic storage duration would be a better choice:

void readLinesFromFile(/*...*/)
{
    char buffer[MAX_LINE];
    // ...
    fgets(&buffer, MAX_LINE, fPtr);
    // ...
}

这篇关于从fgets和strtok的一个文件的读取和解析行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆