读取多个文件,并为每个文件保留一组数据。 [英] Reading multiple files, and keeping a set of data for each file.

查看:142
本文介绍了读取多个文件,并为每个文件保留一组数据。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个文件并将其标题保存在一个变量中,以便当我重写(覆盖)该文件时,我可以粘贴标题,继续打印修改的文件的其余部分。标题,在我的情况下,不会改变,所以我可以负担只是打印出来。这是我的代码里面的类:

I want to read a file and save its header in a variable so that when I am rewriting(overwriting) that file, I can just paste the header and carry on with printing the rest of the modified file. The header, in my case, does not change so I can afford to just print it out. Here is my code inside the class:

.
.
.
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
.
.
.
}

代码成功打印它在读取文件时保存的行,但是我的问题是它保存文件的头所以如果我有两个文件打开,我想保存第一个,然后第二个文件的标题写入第一个。如何避免呢?如果静态映射是一个解决方案,什么确切

The code successfully prints the line it saved while reading the file. However, my problem is that it saves the header of the file it read the last time. So if i have two files opened and I want to save the first one, then the header of the second file is written to the first one. How can I avoid that? If static map is a solution, what exactly is that?

其次,打印整个标题(5-8行)而不是只显示一行的最好方法是。 p>

Secondly, what would be the best way to print the whole header(5-8 lines) instead of only one line as I am doing now.

推荐答案

因此,需要解决的问题是,你正在读取多个文件,并且希望为每个文件保存一组数据。

So, the problem that needs solving is that you are reading multiple files, and want to keep a set of data for each file.

有很多方法可以解决这个问题。其中之一是将 filename 连接。如在注释中建议的,使用 std :: map< std :: string,std :: string> 将是一种方法。

There are MANY ways to solve this. One of those would be to connect the filename with the header. As suggested in a comment, using std::map<std::string, std::string> would be one way to do that.

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. 

这篇关于读取多个文件,并为每个文件保留一组数据。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆