0

I'm doing some simple testing with fopen and fwrite. I'm doing this just to make sure I understand how they work.

I wrote a simple program to create a new file and write one word to it. I'm encountering a problem that I can't figure out.

It creates new file, it writes to the file, but what it writes is not always correct.

For example, at the command line:

./writefile test.txt 1234. Text file is correct and has "1234".

./writefile test.txt 12345. Incorrect, text file is "1234".

./writefile test.txt 123. Incorrect, text file is "123" + a symbol.

It appears to be writing no more than 4 bytes. If less than 4 bytes, it is doing extra filler. If more than 4, it just doesn't write.

What am I missing? Much appreciated.

    #include <stdio.h>
    #include <string.h>


int main (int argc, char* argv[])
{

 // ensure proper usage
    if (argc != 3)
    {
        printf("Usage: ./writefile newfile stringtowrite\n");
        return 1;
    }

// pointer to remember new file 
char* newfile = argv[1];   

//pointer to new word, write to file
char* newword = argv[2]; 

int wordsize = strlen (newword);

FILE* writeptr=fopen(newfile, "w");    

    // check if new file pointer is set correctly. 
    if (writeptr== NULL) 
     {
    fprintf(stderr, "Could not open %s. \n", newfile);
    return 3;
     }

     //write to open file. 
     fwrite(newword, sizeof(wordsize), 1, writeptr);

     //close file 
     fclose(writeptr);
}

1 Answer 1

0

This statement fwrite(newword, sizeof(wordsize), 1, writeptr); will always write 4 bytes. Why? wordsize is an int. Size of an int is 4 bytes. Full stop. Once you supply fwrite with the correct number of bytes to write, your program should work as you expect.

1
  • thank you! I see my mistake now.
    – Xia
    Feb 26, 2016 at 16:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .