2013-01-09 42 views
1

好吧,所以我有一個客戶的結構,我試圖在文本文件中的單獨一行中寫入客戶的每個屬性。下面是代碼不能單獨寫在一個TXT文件中的C

custFile = fopen ("customers.txt", "w+"); 
fprintf(custFile, "%s", cust[cust_index].name); 
fprintf(custFile, "\n"); 
fprintf(custFile, "%s", cust[cust_index].sname); 
fprintf(custFile, "%s", cust[cust_index].id); 
fclose(custFile); 

的數據是形成文本文件在一行

的數據被精細,它只是印刷在一條線輸出。當我給我的朋友寫我的代碼時,它的工作原理應該如此。

P.S我不知道這有什麼差別,但我編程在Mac上

+1

不要刷新標準輸入,它是未定義的行爲。 – effeffe

+0

有關此行爲的說明可以從http://stackoverflow.com/questions/1402673/adding-multiple-lines-to-a-text-file-output – user1929959

+0

中已經給出的答案中推斷出來。不是'\ r' Mac上的換行符? –

回答

1

你的代碼只增加了3個領域的一個新行。它有可能解決了您遇到的問題?如果沒有,請注意老電腦上的一些舊應用程序可能會預期\r行分隔符。

,如果你分解出來的功能,並用它來寫的所有記錄和測試不同的行分隔符

static void writeCustomer(FILE* fp, const Customer* customer, 
          const char* line_separator) 
{ 
    fprintf(fp, "%s%s%s%s%s%s", customer->name, line_separator, 
           customer->sname, line_separator, 
           customer->id, line_separator); 
} 

這將被調用像

writeCustomer(custFile, &cust[cust_index], "\n"); /* unix line endings */ 
writeCustomer(custFile, &cust[cust_index], "\r\n"); /* Windows line endings */ 
writeCustomer(custFile, &cust[cust_index], "\r"); /* Mac line endings */ 

要知道你可以解決這兩個問題某些應用程序不會爲這些行結尾中的某些行顯示換行符。如果您關心在特定編輯器中顯示,請使用不同的行結尾檢查其功能。

+0

我以爲是。我認爲這是過錯。謝謝 – user1961411

+0

'\ r'不是mac上的換行符。 '\ n'是。窗口和所有其他相關係統之間的唯一區別在於窗口有時寫入'\ r \ n'。但使用'\ r'作爲行分隔符的mac是..錯誤的。 http://en.wikipedia.org/wiki/Newline – akira

+0

@ user1961411:不,你的錯是你在'fprintf'調用中不使用_ANY_ linebreaks。 「%s」表示只是「打印一個字符串」而不是「打印一個字符串幷包含換行符」。 – akira