1

我正在尝试读取一个 txt 文件,我可以得到我想要的行,但是我不能一个一个地打印这一行中的每个单词;

例如:该行看起来像:

hello world 1 2 3

我需要一张一张打印出来,看起来像:

hello   
world   
1   
2   
3    

我得到了分段错误核心转储错误

char temp[256];

while(fgets(temp, 256, fp) != NULL) {
    ...
    int tempLength = strlen(temp);
    char *tempCopy = (char*) calloc(tempLength + 1, sizeof(char));
    strncpy(temCopy, temp, tempLength); // segmentation fault core dumped here;
                                     // works fine with temp as "name country"
    name = strtok_r(tempCopy, delimiter, &context);
    country = strtok_r(Null, delimiter, &context);
    printf("%s\n", name);
    printf("%s\n", country);
}

谁能帮我修复代码?
谢谢!

4

2 回答 2

0
While read a line from a file you can invoke the following function:

 if( fgets (str, 60, fp)!=NULL ) {

                            puts(str);
                            token = strtok(str," ");
                            while(token != NULL)
                            {
                                    printf("%s\n",token);
                                    token = strtok(NULL," ");
                            }
                    }
于 2013-10-18T09:11:00.077 回答
0

实现了strtok()

char *p;
char temp[256];

while(fgets(temp,256,fp) != NULL){
  p = strtok (temp," ");
  while (p != NULL)
  {
    printf ("%s\n",p);
    p = strtok (NULL, " ");
  }
}

如果你看到man strtok你会发现

错误

使用这些功能时要小心。如果您确实使用它们,请注意: * 这些函数修改它们的第一个参数。

   * These functions cannot be used on constant strings.

   * The identity of the delimiting character is lost.

   * The strtok() function uses a static buffer while parsing, so it's not thread safe.  Use strtok_r() if this matters to you.

尝试进行更改strtok_r()

于 2013-10-18T09:14:36.293 回答