简体   繁体   English

读取char 0x1A时发生文件结尾

[英]End of File occurs when reading char 0x1A

I am trying to read a file with around 1000 characters in it. 我正在尝试读取其中包含约1000个字符的文件。 The file reading terminates when an 0x1A character is encountered. 遇到0x1A字符时,文件读取终止。 I want that: 我要那个:

  1. 0x1A should not terminate the reading. 0x1A不应终止读取。

  2. 0x1A should be stored like a normal character. 0x1A应该像普通字符一样存储。

Can I use an alternate method of reading the file, maybe? 可以使用其他方法读取文件吗?

int main(void)
{
    int x=0,ch = ' ', file_name[25], arr[1000];
    FILE *fp;

    printf("Enter the name of file you wish to see\n");
    gets(file_name);

    fp = fopen(file_name, "r"); // read mode

    if (fp == NULL)
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    printf("The contents of %s file are :\n", file_name); getchar();

    int y= 0;
    while ((ch = fgetc(fp)) != EOF)
    {
        printf("%d) %x \n",y, ch);
        arr[y++] = ch;
        printf(" %x \n", arr[(y- 1)]);
    }

    printf("Press to see the data off array..."); getchar();
    for (int x = 0; x < y; x++)
    {
        printf("%d ", (x + 1));
        printf(". %x \n", arr[x]);
    }
    getchar();
    fclose(fp);

    return(0);
}

You opened the file as txt mode, 您以txt模式打开文件,

fp = fopen(file_name, "r"); // txt mode

Please try binary mode to read 0x1A ,like 请尝试以二进制模式读取0x1A ,就像

fp = fopen(file_name, "rb"); // binary mode

Instead of fgetc() you can use fgets . 可以使用fgets代替fgetc()

while ((ch = fgetc(fp)) != EOF)
    {
        printf("%d) %x \n",y, ch);
        payload[y++] = ch;
        printf(" %x \n", arr[(y- 1)]);
    }

you can simply write this using fgets() - 您可以简单地使用fgets()编写此代码-

#define MAX 1024
                  //open file in "r" mode 
char arr[MAX];
while(fgets(arr,MAX,fp))
 {
    printf("%s",arr);
 }

Content in you file is stored in array arr . 文件中的内容存储在数组arr While using fgets you don't have to worry about EOF as fgets itself return as it encounters EOF . 使用fgets您不必担心EOF因为fgets在遇到EOF返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM