views:

55

answers:

3

Hi, I'm programming in Windows right now, but portable code would be welcomed too.

What I'm using right now is fwrite(4), but this function needs a maximum number of elements to be written to the file. I can use strlen(1) here but I'd like to know if there is any better way to do this.

+7  A: 

Use fputs instead:

FILE * f = fopen( "myfile.txt", "w" );
fputs( "Hello world\n", f );
anon
A: 

You can use fputs, but using functions that require the size to be written are safer (buffer overrun).

So, IMHO, using fwrite would be the preferred choice.

Am
fwrite gives you no such protection - you have to get the size with strlen(), which does effectively what fputs does
anon
How's fwrite with strlen safer than fputs? Both will overrun the buffer if the string is missing a zero-termination.
roe
Using fwrite with strlen gives no overrun protection, because strlen itself offers no such protection.
gnud
no function really gives this protection. but once you must pass the length you are writing, it is less likely to make BO mistakes.
Am
@Am No you are more likely to make mistakes - for example by supplying a bad length explicitly.
anon
@Neil, True, but it also makes you think about it. Though i cant think of an example that will expose a threat to fputs which won't do it for fwrite+strlen.
Am
@Am: If having to do tedious manual work would make people think harder and thus avoid mistakes, we wouldn't have those thousands of security bugs due to buffer overruns.
sbi
comments accepted, was wrong to mention BO in this scope.
Am
A: 

You might check for a null within the expected length first.

Arthur Kalliokoski