2013-04-14 34 views
1

我打算製作一個python程序來讀取XML文檔,並在做一個動作時用它作爲參考。然而,XML文檔本來是手工創建的乏味,所以我決定做一個C程序來完成它的大部分工作,不包括第一行和根元素。以下是代碼:在使用strsep和fwrite時出現奇怪的輸出C

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(){ 
    FILE * fp = fopen("/Users/rajshrimali/Desktop/SPC_CMS.txt", "r"); 
    FILE * fw = fopen("/Users/rajshrimali/Desktop/SPC_XML", "a"); 
    char *line = NULL; 
    size_t linecap = 0; 
    ssize_t linelen; 
    while ((linelen = getline(&line, &linecap, fp)) > 0){ 
     char *token; 
     int x = 1; 
     while((token = strsep(&line, ",")) != NULL){ 
      printf("%s", token); 
      if(x == 1){ 
       fwrite("<item> \n", linelen, 1, fw); 
       fwrite("<name> \n", linelen, 1, fw); 
       fwrite(token, linelen, 1, fw); 
       fwrite("\n </name> \n", linelen, 1, fw); 
       x++; 
      } 
      if(x == 2) { 
       fwrite("<SPC> \n", linelen, 1, fw); 
       fwrite(token, linelen, 1, fw); 
       fwrite("\n </SPC> \n", linelen, 1, fw); 
       fwrite("</item> \n", linelen, 1, fw); 
      } 
     } 
    } 
} 

該代碼編譯時沒有錯誤。然而,當我運行它,該文件SPC_XML不是接近直角:

<item> 
�<na<name> 

<Agate�0.80 

</name> 
�<SPC> 

</Agate�0.80 

</SPC> 
<</item> 
,�<item> 
<na<name> 

這廢話持續了一段時間。 輸入文件,fp,曾在此格式的數據:

Agate,0.80 
Aluminum bronze,0.436 
Aluminum,0.87 
Antimony,0.21 
Apatite,0.84 

認爲錯誤與fwrite的,雖然我不知道它是什麼。問題是什麼?

回答

2

當您致電fwrite時,第二個參數應該是您正在編寫的字符串的長度。所以,當你這樣做:

fwrite("<item> \n", linelen, 1, fw); 

你最終會寫入額外的數據,或許還不夠,這取決於linelen是。相反,您應該手動計算字符串的大小或在每個字段上調用strlen。所以,上面的電話可以變成:

fwrite("<item> \n", 8, 1, fw); 

,當你寫出來的令牌,你應該叫strlen

fwrite(token, strlen(token), 1, fw); 
+0

謝謝!!!!!這固定它! – elder4222

+0

@ elder4222沒問題。 – Xymostech

2

你必須在這裏您if陳述一些明顯的錯誤,您正在使用=分配的情況下,你應該使用==平等,例如:

if(x = 1) 

應該是:

if(x == 1) 

我會建議打開警告,使用gcc與-Wall -W -pedantic你會看到這樣的事情:

warning: suggest parentheses around assignment used as truth value [-Wparentheses] 
     if(x = 1){ 
+0

我固定的,同樣的問題。 – elder4222

+0

..取決於你正在使用的編譯器,打開編譯器警告的電源。這非常有用。 :) – Jack

+0

沒有給出警告... – elder4222