tags:

views:

72

answers:

4

I read file, but in the end of file i get unknown symbols:

int main()
{
        char *buffer, ch;
        int i = 0, size;
        FILE *fp = fopen("file.txt", "r");
        if(!fp){
                printf("File not found!\n");
                exit(1);
        }
        fseek(fp, 0, SEEK_END);
        size = ftell(fp);
        printf("%d\n", size);
        fseek(fp, 0, SEEK_SET); 
        buffer = malloc(size * sizeof(*buffer));
        while(((ch = fgetc(fp)) != NULL) && (i <= size)){
                buffer[i++] = ch;
        }
        printf(buffer);
        fclose(fp);
        free(buffer);
        getch();
        return 0;
}
+1  A: 

You need to add a null char at the end of buffer before you print:

while(((ch = fgetc(fp)) != NULL) && (i <= size)){
    buffer[i++] = ch;
}
buffer[i] = 0; // add a null char at the end.
printf("%s",buffer); // print using %s format specifier.
codaddict
@OP: You also need to make the size related change as Gregory mentions.
codaddict
+1  A: 

first you need to allocate size + 1 bytes to make room for the terminating NULL character:

buffer = malloc((size + 1) * sizeof(*buffer));

then before printing make sure the string is NULL terminated: buffer[size] = '\0';

finally you're not using printf correctly, it should be

printf("%s", buffer);

see printf manual.

Gregory Pakosz
+1, for catching the size bug..which I missed :)
codaddict
A: 

You seem to be waiting for a NULL character at the end of file, you should really be waiting for an EOF (End of file) character instead.

Change this line:

      while(((ch = fgetc(fp)) != NULL) 

To this:

      while(((ch = fgetc(fp)) != EOF) 
Joe D
+1  A: 

These two strings walk into a bar:

The first string says, "I think I'll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy~~owmc63^Dz x.xvcu"

"Please excuse my friend," the second string says, "He isn't null-terminated."

Martin Beckett