Robert Crawford
Robert Crawford

Reputation: 215

fwrite corrupts my text file

I have been tinkering around for days with a program for a class of mine, and I cannot get fwrite to cooperate. I've tried looking at the online resources for fread and fwrite, looked at my professor's examples, and tried time and time again to fix this, but nothing has worked. No matter what I do, fwrite makes it so that my text editor can't detect any kind of character encoding, so I'm presuming that fwrite is either writing memory addresses or garbage values to the file, making it so that I can't read it. The program is simply supposed to write the contents of one file into another.

Here is my code.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
//initialize files
FILE* infile,  *outfile;
char* buffer;
int read = 0;

//handle the case of having the wrong number of inputs.
if (argc != 4){

    printf("Error: incorrect number of inputs\n");
    //returning 1 will tell us that this was an error (as opposed to returning zero)
    return 1;
}
else{
    //handle the case of not having read acces to file 1
    if ( access(argv[1], R_OK) == 1){

        printf("Error: you do not have read access to the first file\n");
        return 1;
    }
    else {
        //handle the case of not having write access to file 2
        if ( access(argv[2], W_OK) == 1){
            printf("Error: you do not have write access to the second file\n");
            return 1;
        }
        else{
            //handle a bad  buffer size (zero or negative number)
            if ((int)*argv[3] < 0){
                printf("Error: bad input for buffer size.\nBuffer size: %d \n", (int)*argv[3]);
                return 1;
            }
        }
    }
    //open the files in the correct mode.
    infile = fopen(argv[1], "r");
    outfile = fopen(argv[2], "w");


    buffer = malloc((int)*argv[3]);

    while (!feof(infile)){
        read = fread (buffer,1,(int)*argv[3],infile);
        fwrite(buffer,1,(int)*argv[3],outfile);
    }

}
//close files, and deallocate the buffer.
fclose(infile);
fclose(outfile);
free(buffer);
//if we made it here, then that means that our program ran correctly, so return zero.
return 0;
}

Upvotes: 0

Views: 464

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

This is wrong

(int)*argv[3]

change it to

atoi(argv[3])

and it would be better if you store the value somewhere, and check that it's convertible to integer, something like

int size;
char *endptr;

size = strtol(argv[3], &endptr, 10);
if (*endptr != '\0')
    errorNotAnIntegerAbortHere();
buffer = malloc(size);
.
. 
.

not that, *argv[3] would be equivalent to argv[3][0] which is just the first character in argv[3].

Upvotes: 2

Jeff Johnson
Jeff Johnson

Reputation: 2390

fread will return less than the no. of requested bytes at EOF.

Change to

if (read)
    fwrite(buffer,1,read,outfile);

Upvotes: 1

Related Questions