# Trouble with getc ( ) - File I/O

This is a discussion on Trouble with getc ( ) - File I/O within the C Programming forums, part of the General Programming Boards category; Hi, Please review the C program below and see if you can figure out what's wrong. I've been trying for ...

1. ## Trouble with getc ( ) - File I/O

Hi,

Please review the C program below and see if you can figure out what's wrong. I've been trying for a day now and I Just can't seem to get it to work.

The aim of the program is to copy the contents of one file (in.txt) to another (out.txt) using a 256B buffer.

if in.txt contains 4 Chars (eg.ABCD) then out.txt will contain these chars followed by the char 'ÿ' then 252 null characters.

in.txtout.txt

Been cracking my head trying to figure this one out.

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

#define SOURCE  "c:\\dev\\in.txt"
#define DEST    "c:\\dev\\out.txt"
#define BUFF_SIZE 256

signed int buffer[BUFF_SIZE];

int
main (int argc, char *argv[]){

FILE *in, *out;
signed int pos, ch;

if((in = fopen(SOURCE, "r")) == NULL){
fprintf(stderr, "Error: Could not open source file\n");
exit(1);
}

if((out = fopen(DEST, "w")) == NULL){
fprintf(stderr, "Error: Could not open destination file\n");
exit(1);
}

while(!feof(in)){
pos = 0;

while (((buffer[pos] = getc(in)) != EOF) && (pos < BUFF_SIZE)){
pos++;
}

pos = 0;

while (((ch = putc(buffer[pos], out)) != EOF) && (pos < BUFF_SIZE)){
pos++;
}
}

if (fclose(in) == EOF){
fprintf(stderr, "Error: Failed to close input file");
}

if (fclose(out) == EOF){
fprintf(stderr, "Error: Failed to close output file");
}

return 0;
}

2. Why are you using a buffer at all when you only read and write one character at a time anyway? Your whole read/write loop can be replaced with:

Code:
while( (ch = getc(in)) != EOF) {
putc(ch, out);
}
Don't use feof as the loop test btw.

3. Using a buffer was an experiment to see how the Buffer Size would affect copy throughput / Speed...

Is there a bug in my code causing the output file to appear corrupt ??

4. Originally Posted by The_KD
Using a buffer was an experiment to see how the Buffer Size would affect copy throughput / Speed...
Then use fread and fwrite, you are still reading and writing 1 character at a time regardless of your buffer or its size.

Originally Posted by The_KD
Is there a bug in my code causing the output file to appear corrupt ??
What do you think?

5. Originally Posted by The_KD
Is there a bug in my code causing the output file to appear corrupt ??
Yes. You use pos to count the number of characters read, but then you don't use pos to control the number of characters to write. If you did this correctly, your use of feof would be okay here, though unnecessary since you just need to terminate the loop once no characters are to be written.