Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is fwrite writing more than I tell it to?

Tags:

c

file

fwrite

ftell

FILE *out=fopen64("text.txt","w+");
unsigned int write;
char *outbuf=new char[write];
//fill outbuf
printf("%i\n",ftello64(out));
fwrite(outbuf,sizeof(char),write,out);
printf("%i\n",write);
printf("%i\n",ftello64(out));

output:

0
25755
25868

what is going on? write is set to 25755, and I tell fwrite to write that many bytes to a file, which is at the beginning, and then im at a position besides 25755?

like image 389
zacaj Avatar asked Oct 19 '09 00:10

zacaj


People also ask

Is fwrite binary?

fread() and fwrite() functions are commonly used to read and write binary data to and from the file respectively.

Where does fwrite write to?

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

What does fwrite mean in C?

(Write Block to File) In the C Programming Language, the fwrite function writes nmemb elements (each element is the number of bytes indicated by size) from ptr to the stream pointed to by stream.

Is fwrite safe?

fwrite() is a function that writes to a FILE*, which is a (possibly) buffered stdio stream. The ISO C standard specifies it. Furthermore, fwrite() is thread-safe to a degree on POSIX platforms.


1 Answers

If you are on a DOSish system (say, Windows) and the file is not opened in binary mode, line-endings will be converted automatically and each "line" will add one byte.

So, specify "wb" as the mode rather than just "w" as @caf points out. It will have no effect on Unix like platforms and will do the right thing on others.

For example:

#include <stdio.h>

#define LF 0x0a

int main(void) {
    char x[] = { LF, LF };

    FILE *out = fopen("test", "w");

    printf("%d", ftell(out));
    fwrite(x, 1, sizeof(x), out);
    printf("%d", ftell(out));

    fclose(out);
    return 0;
}

With VC++:

C:\Temp> cl y.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

y.c
Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:y.exe

C:\Temp> y.exe
04

With Cygwin gcc:

/cygdrive/c/Temp $ gcc y.c -o y.exe

/cygdrive/c/Temp $ ./y.exe
02
like image 121
Sinan Ünür Avatar answered Oct 11 '22 23:10

Sinan Ünür