用C/C++阅读本文

reading this text in C/C++

本文关键字:C++      更新时间:2023-10-16

嗨,我正试图使用文件输入流或某种排序读取此文本:

E^@^@<a^R@^@@^FÌø<80>è^AÛ<80>è  ^F ^DÔVn3Ï^@^@^@^@ ^B^VÐXâ^@^@^B^D^E´^D^B^H
IQRÝ^@^@^@^@^A^C^C^GE^@^@<^@^@@^@@^F.^K<80>è    ^F<80>è^AÛ^DÔ »4³ÕVn3Р^R^V J  ^@^@^B^D^E´^D^B^H
^@g<9f><86>IQRÝ^A^C^C^GE^@^@4a^S@^@@^FÌÿ<80>è^AÛ<80>è   ^F ^DÔVn3л4³Ö<80>^P^@.<8f>F^@^@^A^A^H
IQRÞ^@g<9f><86>E^@^A±,Q@^@@^F^@E<80>è   ^F<80>è^AÛ^DÔ »4³ÖVn3Ð<80>^X^@.^NU^@^@^A^A^H
^@g<9f><87>

这是我试着读的代码,但我得到了一堆0。

    #include <stdio.h>   /* required for file operations */
int main(int argc, char *argv[]){
  int n;
  FILE *fr;
  unsigned char c;
  if (argc != 2) {
    perror("Usage: summary <FILE>");
    return 1;
  }
  fr = fopen (argv[1], "rt");  /* open the file for reading */
  while (1 == 1){
    read(fr, &c, sizeof(c));
    printf("<0x%x>n", c);
  }
  fclose(fr);  /* close the file prior to exiting the routine */
}

我的代码出了什么问题?我想我没有正确阅读这个文件。

您使用fopen()打开文件,返回FILE *,使用read()读取文件,需要int。您需要同时使用open()read(),或者fopen()fread()。你不能把这些混在一起。

为了澄清,fopen()fread()使用了FILE指针,这是一种不同于直接文件描述符的访问方式和抽象。open()read()使用"原始"文件描述符,这是操作系统所理解的概念。

虽然这里与程序的失败无关,但您的fclose()调用也必须匹配。换句话说,fopen()fread()fclose(),或者open()read()close()

你的没有为我编译,但我做了一些修复,一切顺利;-)

  #include <stdio.h>   /* required for file operations */
  int main(int argc, char *argv[]){
    int n;
    FILE *fr;
    unsigned char c;
    if (argc != 2) {
      perror("Usage: summary <FILE>");
      return 1;
    }
    fr = fopen (argv[1], "rt");  /* open the file for reading */
    while (!feof(fr)){  // can't read forever, need to stop when reading is done
      // my ubuntu didn't have read in stdio.h, but it does have fread
      fread(&c, sizeof(c),1, fr);
      printf("<0x%x>n", c);
    }
    fclose(fr);  /* close the file prior to exiting the routine */
  }

这对我来说不像文本。所以对fopen使用"r"模式,而不是"rt"

此外,^@表示'',所以在任何情况下,您都可能读取一堆零。但不是全零。

相关文章:
  • 没有找到相关文章