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)
code每次读取一个字符时都会增加,然后返回code给调用者(即使它不再指向内存块的第一个字节,因为它返回了malloc).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.
从@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)
这将为您提供文件的长度,然后逐个字符地读取它.