Search code examples
cprintffopenfwritefread

Why wont my code work to open a new file using sprintf and fopen?


int main()
{
    int size = 512, i = 1;
    char buffer[1000];
    char *newFileTemp;
    char const *chunk = "Chunk";
    memset(buffer, 0, sizeof(buffer));
    FILE *fb;
    FILE *fp=fopen("blah.txt", "r");
    if (fp == NULL)
    {
        perror("doesnt exist");
        return 0;
    }

     fread(buffer,sizeof(char),sizeof(buffer), fp);
     sprintf(newFileTemp, "%s%i", chunk, i);

     printf("blah check %s",newFileTemp);
     fb = fopen(newFileTemp, "wb");
     if (fb == NULL)
     {
         perror("doesnt exist");
         return 0;
     }
     fwrite(buffer, sizeof(char), sizeof(buffer), fb);

     fclose(fp);
     fclose(fb);

     return 0;
}

I'm trying to use sprintf to create a new file named chunk1 that has the data of file blah.text (blah.txt is already created). But even though the code compiles properly, it doesn't create a new file. Please help.


Solution

  • What you are experiencing is called an undefined behaviour, because you are using newFileTemp before you have initialized it. To correct the problem, initialize it like this:

    newFileTemp = (char*)malloc(100);
    

    or declare it like this:

    char newFileTemp[100];
    

    The reason is that sprintf expects newFileTemp to have enough space allocated for storing the string it is formatting (it will not allocate it for you).

    Also:

    • If you use malloc don't forget to free.

    • Don't forget to check the success of functions like fread and fwrite.

    • You'll have another problem later because in your call to fwrite you are trying to write always 1000 bytes (sizeof(buffer) is 1000 bytes), even if your file had fewer bytes. This is where the return value of fread comes into play (it returns the actual amount of bytes read): you need to use that return value instead of sizeof(buffer).