我想读取一个文件并将它的头文件保存在一个变量中,这样当我重写(覆盖)该文件时,我可以只粘贴头文件并继续打印修改后的文件的其余部分。在我的例子中,标题不会改变,所以我可以打印出来。下面是我在类中的代码:
.
.
.
static char headerline[1024];
static int read(const char* filename){
fget(var,...;
for (int i=0; i<1024; ++i){
headerline[i] = var[i];
}
.
.
.
}
int write(filename){
fprintf(filename, headerline);
//printing rest of file
.
.
.
}代码成功地打印出它在读取文件时保存的行。然而,我的问题是它保存了上次读取的文件头。因此,如果我打开了两个文件,并且我想保存第一个文件,那么第二个文件的头就会写入第一个文件。我该如何避免这种情况呢?如果静态映射是一种解决方案,那么它到底是什么呢?
其次,打印整个页眉(5-8行)的最佳方式是什么,而不是像我现在这样只打印一行。
发布于 2013-05-14 20:50:19
因此,需要解决的问题是,您正在读取多个文件,并且希望为每个文件保留一组数据。
有很多方法可以解决这个问题。其中之一是将filename与header连接起来。正如评论中所建议的,使用std::map<std::string, std::string>将是实现这一目标的一种方法。
static std::map<std::string, std::string> headermap;
static int read(const char* filename){
static char headerline;
fget(var,...;
for (int i=0; i<1024; ++i){
headerline[i] = var[i];
}
headermap[std::string(filename)] = std::string(headerline);
...
int write(filename){
const char *headerline = headermap[std::string(filename)].c_str();
fprintf(filename, headerline);
// Note the printf is based on the above post - it's wrong,
// but I'm not sure what your actual code does. 发布于 2013-05-14 20:25:25
你应该对不同的文件使用不同的头变量。
https://stackoverflow.com/questions/16543042
复制相似问题