Question

Never used fwrite(), so I'm not sure exactly what I'm doing wrong. I'm just testing it now and all I want to do is try to write a single char out to a file until it reaches the end. The file I'm writing to is one I downloaded from my teacher's website. When I check the properties of it, the type is only listed as "file". It's supposed to just be an empty 2MB file for us to write our code to (file system lab if anyone's wondering). Here's my code:

#include <stdio.h>
#include <string.h>
int main()
{
    char c;
    FILE *fp;   
    char testing[2] = {'c'};  

    fp = fopen("Drive2MB", "rw"); 

    fseek(fp, 0, SEEK_SET);     //make sure pointers at beginning of file
    while((c=fgetc(fp))!=EOF)
    {
        fwrite(testing, 1, sizeof(testing), fp);
        fseek(fp, 1, SEEK_CUR);  //increment pointer 1 byte
    }
    fclose(fp);
} 

When I run this, an error message pops up saying "Debug Assertion Failed!...Expression:("Invalid file open mode",0) and prints "The program '[3896] filesystem.exe: Native' has exited with code 3 (0x3)."

Was it helpful?

Solution

You have opened the file for reading (that's what the r stands for in fopen("Drive2MB", "r");). You may not write to a file opened for reading.

OTHER TIPS

You're opening it in read only mode

Use r+ for the fopen

fp = fopen("Drive2MB", "r")

your openning your file in read only

try

fp = fopen("Drive2MB", "r+"); 

You've opened the file for reading with the "r" part of fopen. To write to the file, you can open it in read/write mode or write mode.

// Read/write mode
fp = fopen("Drive2MB", "r+");

// Write only mode
fp = fopen("Drive2MB", "w");

I never like to use "rw" personally. When you open a file, it really should have one reason to be opened. You also do not need to call fseek to move to the start of the file and you do not need to use fseek to advance the file pointer. fopen will automatically open it to the start of the file and fwrite will automatically advance the pointer. fseek should only be used if you are "seek"ing inside of the file to get to a specific point.

In the case you've given, you would only need write ("w") mode since you are not ever reading from the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top