gpt4 book ai didi

c++ - 如何同时打开多个文件以在c中读取

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:21 26 4
gpt4 key购买 nike

我正在尝试将我的一些 C++ 代码移植到 C 中。我有以下构造

class reader{
private:
FILE *fp;
alot_of_data data;//updated by read_until() method
public:
reader(const char*filename)
read_until(some conditional dependent on the contents of the file, and the arg supplied)
}

然后我实例化了数百个这样的对象,并为每个文件使用多个“read_until()”迭代它们,直到所有文件都位于 eof。

我没能在 C 中看到任何聪明的方法来做到这一点,我能想出的唯一解决方案是创建一个 FILE 指针数组,并对我类中的所有私有(private)成员数据执行相同的操作。

但这看起来很困惑,我可以将我的类的功能实现为函数指针,还是更好的东西,我想我缺少一个基本的设计模式?

这些文件太大了,无法全部放在内存中,因此从每个文件中读取所有内容是不可行的谢谢

最佳答案

您创建一个抽象数据类型:

typedef struct {
FILE *fp;
alot_of_data data;//updated by read_until() method
} reader;

void init_reader(reader* that, const char* filename);
void read_until(reader* that, some conditional dependent on the contents of the file, and the arg supplied)

然后你可以创建和使用这种类型的对象,就像使用类的对象一样,除了,而不是 obj.func()。 , 你写 func(&obj) :

reader r;
init_reader(&r, "blah.txt");
read_until(&r, /* ... */);

关于c++ - 如何同时打开多个文件以在c中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com