2012-09-13 54 views
0

我正在處理文件。我想把每一行都分開,並在空格後分開。 例如,如果一號線有:今天是星期一我希望能有今天,是,週一separatly爲了對他們的工作將文本添加到行尾

這是到目前爲止我的代碼:

FILE *file = fopen ("file1", "r"); 

      if ((file != NULL)) 
      { 
       char line [ 128 ]; 
       while((fgets (line, sizeof line, file) != NULL)) 
       { 
       //tokenize the line based on space 

       ?? 

       } 
how to add text at the end of the line? i mean i have **today is monday** and i want to add for example **Yupppy** at the end of today is monday line. 

      fclose (file); 

      } 
+1

你可以使用strtok – Vijay

+0

可以請你發表一個例子嗎?thx –

+0

我還需要在每行的結尾添加一個新的工作。你可以幫我嗎?thx –

回答

-1

來標記一個字符串即可使用strtok() 檢查我的鏈接後的例子,只是改變分隔空間:

(從鏈接的示例代碼)

#include <stdio.h> 
#include <string.h> 




int main() 
{ 
  char str[] ="- This, a sample string."; 
  char * pch; 
  printf ("Splitting string \"%s\" into tokens:\n",str); 
  pch = strtok (str," "); 
  while (pch != NULL) 
  { 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " "); 
  } 
  return 0; 
} 
+0

當然,應該注意的是'strtok'不是可重入的,應該使用'strtok_r'而不是可用的(甚至是'strsep',我認爲它更清潔)。 –

+0

我正在c。謝謝。以及如何在char []的末尾添加單詞? –

+0

你能幫忙嗎? –