1

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

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

1

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.

simonc
  • 41,632
  • 12
  • 85
  • 103
  • `\r` is not a newline on mac. `\n` is. the only diff between windows and all other relevant systems is that windows sometimes writes a `\r\n`. but mac using `\r` as the line separator is .. wrong. http://en.wikipedia.org/wiki/Newline – akira Jan 09 '13 at 13:37
  • @user1961411: and no, your fault is that you do not use _ANY_ linebreaks in your `fprintf` calls. "%s" means just "print a string" and not "print a string AND include the linebreak". – akira Jan 09 '13 at 13:38
  • @akira Both the wikipedia link you posted and [this previous SO question](http://stackoverflow.com/questions/1279779/what-is-the-difference-between-r-and-n) say that recent Macs use \n for newlines but older ones used \r. Is my updated answer any better or do you still think its wrong? – simonc Jan 09 '13 at 13:42
  • @simonc: do you know how old your mac has to be to use `\r` as line-ending? do you consider 10years+ as important as to put that part of your answer to the top? it's a sidenote at best, just use `\n` and done. wordpad on windows will open such files very well, any other sane text-editor on the planet loves `\n`. – akira Jan 09 '13 at 14:49