从文本文件中的一行中获取每个单词

时间:2013-10-18 08:55:25

标签: c

我正在尝试读取一个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);
}

任何人都可以帮我修复代码吗? 谢谢!

2 个答案:

答案 0 :(得分: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," ");
                            }
                    }

答案 1 :(得分: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您将找到

<强> BUGS

  

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

   * 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()

进行更改