0
votes

I've been trying to figure out how to use fread and fwrite to read in file pointers to no avail. I'm creating a very simple program to read in a file, use fseek and ftell to determine the size, and finally write the contents of the first file to the second. My code compiles but produces no output, which I think is due to my faulty fwrite functions??

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

int main(int argc, char **argv)
{
    FILE *infp;
    FILE *outp;
    char *str;
    size_t place;
    infp = fopen(argv[1], "r");
    if (infp==NULL) 
    {
        fputs ("File error",stderr); 
        exit (1);
    }
    outp = fopen(argv[2], "w");
    int count = 0;
    fseek(infp,0,SEEK_END);
    long size = ftell(infp);
    rewind(infp);
    str = (char *)malloc(sizeof(char)*size);
    if (str == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }
    place = fread(str, sizeof(char), size, infp);
    if (place != size) 
    {
        fputs ("Reading error",stderr); 
        exit (3);
    }
    fwrite(str, 1, place, infp);
    fclose(infp);
    fclose(outp);
    free(str);
}
1
You write to infp, but you want to write to outp, of course. - M Oehm
(And you should check whethet there are at least two extra arguments in argv and that outp could be opened for writing.) - M Oehm
Your code correctly checks that it was able to open the input file; it does not check that it was able to open the output file. It should. - Jonathan Leffler
More like if (argc != 3) { fprintf(stderr, "Usage: %s infile outfile\n", argv[0]); exit(1); }. - Jonathan Leffler
Leave your hair in peace. It may look like a dumb mistake in retrospect, but that's the kind of error you can look at for hours and not see it. Your check looks okay, but the more important case to catch is when there are fewer than 3 arguments and the fopen call use ´NULL´ filenames - M Oehm

1 Answers

0
votes

You have a typo. Change:

fwrite(str, 1, place, infp);

To:

fwrite(str, 1, place, outp);