2013-01-09 40 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