开发者

Unknown symbols when I read file

开发者 https://www.devze.com 2022-12-24 03:42 出处:网络
I read file, but in the end of file i get unknown symbols: int main() { char *buffer, ch; int i = 0, size;

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

int main()
{
        char *buffer, ch;
        int i = 0, size;
        FI开发者_如何学PythonLE *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;
}


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.


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.


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."


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) 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号