the program is stuck writing contents to the file in c

Time for some basic debugging. I’d suggest changing your read loop to something like this:

while (total_bytes_read < filesize) {
    printf("DEBUG A: total=%zu, size=%zu\n", total_bytes_read, filesize);
    while ((bytes_read = read(sd, buf, sizeof(buf))) > 0) {
        printf("DEBUG B: read=%zd\n", bytes_read);
        fwrite(buf, 1, bytes_read, fp);
        total_bytes_read += bytes_read;
        printf("DEBUG C: total=%zu\n", total_bytes_read);
        if (ferror(fp))
            printf("DEBUG D\n");
            perror("error");
            fclose(fp);
        }
        printf("DEBUG E\n");
    }
    printf("DEBUG F\n");
}
printf("DEBUG G\n");

Then run it, piping the output through less or some other pager, it should then hopefully become clearer what’s actually happening.

Feel free to post the output of this modified code (in a comment, or in the actual question), we’ll no doubt be able to help with the analysis.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top