在C中逐个字符地读取文件

Dev*_*gay 29 c io file-io iostream

大家好,我正在用C编写一个BF解释器,我遇到了读文件的问题.我曾经使用scanf来读取第一个字符串,但是你的BF代码中没有空格或注释.

现在这就是我所拥有的.

char *readFile(char *fileName)
{
  FILE *file;
  char *code = malloc(1000 * sizeof(char));
  file = fopen(fileName, "r");
  do 
  {
    *code++ = (char)fgetc(file);

  } while(*code != EOF);
  return code;
}
Run Code Online (Sandbox Code Playgroud)

我知道问题出现在我如何将文件中的下一个字符分配给代码指针但我不确定那是什么.
我的指针知识缺乏,这是本练习的重点.解释器工作正常,都使用指针,我只是在读取文件时遇到问题.

(我打算稍后只在文件中读取"+ - > <[].",尽管如果有人有好的方法,如果你让我知道的话会很棒!)

提前致谢

dre*_*lax 37

您的代码有很多问题:

char *readFile(char *fileName)
{
    FILE *file;
    char *code = malloc(1000 * sizeof(char));
    file = fopen(fileName, "r");
    do 
    {
      *code++ = (char)fgetc(file);

    } while(*code != EOF);
    return code;
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果文件大于1,000字节怎么办?
  2. code每次读取一个字符时都会增加,然后返回code给调用者(即使它不再指向内存块的第一个字节,因为它返回了malloc).
  3. 您是铸造的结果fgetc(file)char.您需要EOF在将结果转换为之前检查char.

保持返回的原始指针非常重要,malloc以便以后可以释放它.如果我们忽略文件大小,我们仍然可以通过以下方式实现此目的:

char *readFile(char *fileName)
{
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL)
        return NULL; //could not open file

    code = malloc(1000);

    while ((c = fgetc(file)) != EOF)
    {
        code[n++] = (char) c;
    }

    // don't forget to terminate with the null character
    code[n] = '\0';        

    return code;
}
Run Code Online (Sandbox Code Playgroud)

有各种系统调用可以提供文件的大小; 一个常见的是stat.

  • @deamlax你的例子似乎有一个小错字.`fgets`需要多个参数.你的意思是'fgetc`吗? (4认同)

Jus*_*tin 8

从@dreamlax扩展上面的代码

char *readFile(char *fileName) {
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL) return NULL; //could not open file
    fseek(file, 0, SEEK_END);
    long f_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    code = malloc(f_size);

    while ((c = fgetc(file)) != EOF) {
        code[n++] = (char)c;
    }

    code[n] = '\0';        

    return code;
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供文件的长度,然后逐个字符地读取它.

  • 将“fseek”视为重新定位光标的一种方法。fseek(文件, 0, SEEK_END); 将光标放在文件末尾,然后“ftell”告诉您光标在哪里。这将为您提供文件的大小。`fseek(file, 0, SEEK_SET);` 将光标放回到文件的开头,以便可以读取它。如果不这样做,您将从末尾开始读取文件,这将导致错误并破坏整个操作。 (2认同)