APaul APaul - 2 months ago 13
C Question

fwrite() fails without writing anything to existing file

Sorry for this basic problem guys, but I'm having an issue just getting

fwrite()
to work properly?

#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main() {

FILE* fd = NULL;
fd = fopen("out","rw");

if (fd == NULL) {
printf("Open failed\n");
return -1;
}

int error = 0;

printf("Attempting write ... \n");
char buff[] = {"hello?\n"};

if( (error = fwrite(buff, 1, 7, fd)) != 7 ) {
printf("fwrite() failed with code %d \n", error);
return -1;
}

fclose(fd);

return 0;
}


This code fails -
fwrite()
just returns 0 when it should return 7 instead for seven 1b characters written to the file. The file does exist in the same directory; I've tried this with the full file path instead; I've chmod'd the output file
out
to 777 in case that was the issue (it wasn't);
fread()
and
fseek()
both work as expected but I've taken them out for brevity.

What am I doing wrong here? Any help is appreciated.

Answer

fopen do not have "rw" mode, and you should open the file in binary mode since you fwrite to it.

What you want is "wb", "w+b" or "r+b"