Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Problem with C fwrite

Name: Anonymous 2007-11-08 12:51

What the fuck? Why, when I try to write a string to a text file using C, does it change the first character to "ÿ"?

e.g.

ÿ10
ÿhis
ÿololol
ÿhis

(all input on different runs of the program).

I'm using "a+" if that makes any difference, though I've tried with "r+" aswell and that does the same thing.

Any help?

Name: Anonymous 2007-11-08 14:55

>>8
First, don't use gets. You will be raped in the ass repeatedly by a hairy spoon-wielding monkey whose sole purpose is to rape people who use gets in the ass. Instead use fgets, using stdin as the file handle to get from.

Second, you never initialize your buffer. Sure, you read in some bits from stdin, but that doesn't null-terminate your string. This has the effect of a hard-coded buffer overflow and rapes your stack; the rest of the code's behavior is undefined.

So you'll need to null-terminate the buffer. The cheap (and incorrect) way to do this is to just name[sizeof(name)/sizeof(char)-1] = 0. While this does set the last character to the null character, you've still got a shitton of uninitialized garbage in there. Use memset to zero the entire buffer (shown later).

Another gripe is that you don't need to fseek when you've set the mode to "a". Append does this automatically; you only need to do a seek operation when opening the file in an r mode.

Finally fclose the motherfucking file when you're done with it.

Here's my version of your code, which appears to work when compiled with gcc:

#include <stdio.h>

int main( int argc, char* argv[] )
{
    char name[20];
    memset( name, 0, sizeof( name ) / sizeof( char ) ); 
                
    printf( "\nname: " );
    fgets( name, sizeof( name ) / sizeof( char ) - 1, stdin ); 
    FILE *input = fopen( "file.txt", "a" );
                                            
    if( input != NULL )
    {
        fwrite( name, sizeof( char ), sizeof( name ) / sizeof( char ), input );
    }
                                            
    fclose( input );
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List