【发布时间】:2018-02-27 14:41:46
【问题描述】:
我似乎无法弄清楚如何从 fopen 转换为 open。我没有太多的c经验,所以这对我来说是相当压倒性的。
这是它自己的东西:
在 cache_reader.c 文件中(只是打开和关闭函数):
void cr_close(cr_file* f){
free(f->buffer);
fclose(f->file);
}
cr_file* cr_open(char * filename, int buffersize)
{
FILE* f;
if ((f = fopen(filename, "r")) == NULL){
fprintf(stderr, "Cannot open %s\n", filename);
return 0; }
cr_file* a=(cr_file*)malloc(sizeof(cr_file));
a->file=f;
a->bufferlength=buffersize;
a->usedbuffer=buffersize;
a->buffer=(char*)malloc(sizeof(char)*buffersize);
refill(a);
return a;
}
在cache_reader.h文件中:
typedef struct{
FILE* file; //File being read
int bufferlength; //Fixed buffer length
int usedbuffer; //Current point in the buffer
char* buffer; //A pointer to a piece of memory
// same length as "bufferlength"
} cr_file;
//Open a file with a given size of buffer to cache with
cr_file* cr_open(char* filename, int buffersize);
//Close an open file
void cr_close(cr_file* f);
int refill(cr_file* buff);
在 cache_example.c 文件中:
int main(){
char c;
//Open a file
cr_file* f = cr_open("text",20);
//While there are useful bytes coming from it
while((c=cr_read_byte(f))!=EOF)
//Print them
printf("%c",c);
//Then close the file
cr_close(f);
//And finish
return 0;
}
我知道我需要将 fclose 更改为关闭,将 fopen 更改为打开。但我不明白大多数其他的东西。我遇到了很多错误,我不确定指针是如何解决的,因为我对它们几乎没有任何经验。我尝试使用 int fileno(FILE *stream),通过说 int fd = fileno(FILE *f) 然后 fd = fopen(filename, "r")) == NULL)。这不起作用,我能找到的所有 open 函数示例都只使用文件名,而不是字符指针来指定文件名......我认为 cr_close 函数可以通过将 fclose 更改为 close 来完成,但这也不起作用。我不确定是否还需要编辑 cache_example.c 文件。
谁能提供一些帮助,让我走上正确的道路……?
【问题讨论】:
-
你觉得文件名和指向
char的指针有什么区别? -
练习的目的是保持示例代码不变,但重新实现其他代码以使用文件描述符而不是文件流。遗憾的是,标题不必要地暴露了结构的内部,因此需要重新编译示例。您将
FILE *成员更改为int。您不会使用任何带有文件流参数的函数。 -
如何将 FILE * 更改为 int..?我认为 fileno 函数会做我试图做的事情。我还尝试将 fprintf 更改为 printf 并将 stderr 更改为 stdout 以使其工作。还是不行。
-
注意:更改
char c-->int c以避免不正确的行为。