Reading multiple files, and keeping a set of data

2019-09-16 09:02发布

问题:

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?

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.

回答1:

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

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. 


回答2:

You should use different header variables for different files.



标签: c++ static