Web Hosting Talk







View Full Version : Something really basic in C...


akbsol
08-08-2007, 12:21 AM
Hi everyone,

I must be ignoring something really basic but please anyone tell me what is the problem with the following code. Its a simple program to create a temporary file containing all command line arguments one per line (seperated by CRLFs). The code compiles fine in VC++ but when the generated exe is run, it creates the file with command line arguments seperated by CRCRLFs (\r\r\n) instead of CRLFs (\r\n).


#include <stdio.h>

main(int argc, char *argv[])
{
FILE *f;
int i;
char g[] = "C:\\temp\\XXXXXX";
char *h;
char *mktemp();
h = mktemp(g);

f = fopen(h, "w");
for(i=0;i<argc;i++)
{
fputs(argv[i], f);
fputs("\r\n", f);
}
fclose(f);
}

Regards,
Akash

akbsol
08-08-2007, 12:32 AM
It seems using "wb" in place of "w" for fopen solved the problem but i am still wondering why this different behaviour for binary files.

mwatkins
08-08-2007, 03:33 AM
Various OS's have different conventions for what defines a "newline".
Unix - \n
Windows \r\n
Mac \r

In binary mode what you write is what you get; there is no automatic translation of newlines going on, which is likely what you are experiencing.

Some higher level languages (Python for example) do automatic newline translation depending on OS -- in your apps you always represent the newline as \n and files written will adapt to the underlying OS.

akbsol
08-08-2007, 03:55 AM
"In binary mode what you write is what you get; there is no automatic translation of newlines going on, which is likely what you are experiencing"

Thanks

Engelmacher
08-08-2007, 01:46 PM
Mac \r

Your information is several years out of date.

mwatkins
08-08-2007, 02:07 PM
Your information is several years out of date.

If you wish to be pedantic then I have to point out that my information isn't out of date, just not specific. I could have been more specific and added that my reference to "Mac" meant Mac OS < X, since "Unix" includes Mac OS >= X.

There are still a goodly number of machines running Mac OS < X.

bqinternet
08-08-2007, 09:01 PM
It seems using "wb" in place of "w" for fopen solved the problem but i am still wondering why this different behaviour for binary files.

When you're writing in ASCII mode, Windows is converting your \n to \r\n. Since you're writing \r\n, Windows makes it \r\r\n