0
FILE* inFile = fopen(inF, "rb");
if (inFile == NULL) {
    printf("Invalid input!\n");
    exit(EXIT_FAILURE);
}

char* bigBuffer;
char* nextChar = (char*) malloc(sizeof(char));
unsigned long i = 0;
unsigned long j;
while ((j = fread(nextChar, sizeof(char), 1, inFile)) == 1) {
    i += j;
}
bigBuffer = malloc(i * sizeof(char));
fread(bigBuffer, sizeof(char), i, inFile);
fclose(inFile);
printf("%s\n", outF);
FILE* outFile = fopen(outF, "wb");
//if (outFile == NULL)
    //printf("null\n");
j = fwrite(bigBuffer, sizeof(char), i, outFile);
printf("%lu\n", j);
fclose(outFile);
free (bigBuffer);
free (nextChar);

I'm trying to write a binary file using fopen in wb mode. After running my program, a file of the proper name is made in the proper place, but I just can't open it or read it. When I try to open it, a message pops up saying "Can't open...." In addition, the name of the file itself isn't formatted properly in Finder (I'm on a Mac). The name is elevated and cut off a little. It definitely looks like something is wrong with the file. I tried just making a regular file using fopen in w mode, and that worked beautifully. So I'm pretty sure I'm just doing something wrong when it comes to writing binary files using wb mode. Can anyone help? Thanks.

Cal
  • 5
  • 1

2 Answers2

2

The main problem:

  • you didn't seek to the beginning of the file before reading, so your call to fread to read the entire file will fail

Change:

bigBuffer = malloc(i * sizeof(char));
fread(bigBuffer, sizeof(char), i, inFile);

to:

bigBuffer = malloc(i);              // allocate buffer
rewind(inFile);                     // reset file pointer to start of file
fread(bigBuffer, 1, i, inFile);     // read entire file

Additional notes:

  • sizeof(char) is 1 by definition, and therefore redundant
  • you should not cast the result of malloc in C
  • you should add error checking to any call that might fail, especially I/O calls
  • malloc-ing a single char is inefficient - just use a local variable
  • reading a file one char at a time to determine its length is very inefficient
Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Sir, `you have no '\0' terminator in your string when calling printf`...which one you're referring to? – Sourav Ghosh Nov 16 '15 at 13:51
  • 1
    Makes sense. However,we cannot rule out the possibility that OP wants to see if the out file name is proper or not. In that case, without seeing more code, we cannot conclude. Am I right? – Sourav Ghosh Nov 16 '15 at 13:53
  • 1
    @SouravGhosh: oh yes, maybe - it's not totally clear what the intention is, but I'll edit that stuff out for now. – Paul R Nov 16 '15 at 13:54
0

The file with the opening in wb truncated to 0 length. Use for simultaneous read / write mode or addition mode rb +, a.

Spouk
  • 691
  • 7
  • 18