APaul APaul - 1 year ago 80
C Question

fwrite() fails without writing anything to existing file

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

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;


return 0;

This code fails -
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
to 777 in case that was the issue (it wasn't);
both work as expected but I've taken them out for brevity.

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

Answer Source

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"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download