user1961411
user1961411

Reputation: 33

Cannot write in separate lines in a TXT files in C

ok so i have a structure of customers and i am trying to write each attribute of the customer in a separate line in a text file. Here is the code

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);

The data is form the text file is outputted in one line

The data is fine, it is just printed in one line. When i gave my friend my code, it worked as it should.

P.s i dont know if it makes any difference but i am programming on a mac

Upvotes: 1

Views: 374

Answers (1)

simonc
simonc

Reputation: 42175

Your code only adds one newline for the 3 fields. Its possible this accounts for the problems you've encountered? If not, note that some old apps on old macs may expect \r line separators.

You could address both issues if you factored out a function and used it to write all records and to test out different line separators

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);
}

which would be invoked like

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 */

Be aware that some apps won't display newlines for some of these line endings. If you care about display in particular editors, check their capabilities with different line endings.

Upvotes: 1

Related Questions