1830241 Members
7501 Online
109999 Solutions
New Discussion

Re: C++ file operations.

 
Tnameh
Occasional Advisor

C++ file operations.

Hello All
I need lib routine in C++, which update particular value in file.

I wll have, a huge file and function wuld search for Key update value of KEY to YES/NO

Can anybody help me in getting libaray which does this operation i.e open source or any good code that does so.


ABC:YES
DEF:NO
CEF:YES
GEF:KEY

It should be in c++ and efficent way of doing it.

3 REPLIES 3
Peter Godron
Honored Contributor

Re: C++ file operations.

Hi,
could you please provide an example input and output file. It may be a lot faster to use UNIX commands to perform updates to selected lines.
Tnameh
Occasional Advisor

Re: C++ file operations.

Thanks but i dont need any unix command or script. It should be pure C++ functions

Example. I have file.cfg.
Where ABC, DEF,CEF etc are configuration, and have to set corresponding value for it.

ABC:YES
DEF:NO
CEF:YES
GEF:NO

But its just a snapshort. but file can be bit larger.
Dennis Handly
Acclaimed Contributor

Re: C++ file operations.

Here is a C++ program (:-) that uses stdio to read a file and output the changes to stdout:
$ aCC -AA itrc_update.C
$ a.out itrc_update.in GEF maybe
ABC:YES
DEF:NO
CEF:YES
GEF:maybe

itrc_update.C:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv) {
    int len;
    char line[4096];
    if (argc < 4) {
       fprintf(stderr, "Usage: %s input key value\n", argv[0]);
       return 1;
    }
    FILE *f = fopen(argv[1], "r");
    if (!f) {
       fprintf(stderr, "Can't open %s\n", argv[1]);
       perror("Open failed");
       return 2;
    }
    int len_key = strlen(argv[2]);
    int len_val = strlen(argv[3]);
    while (fgets(line, sizeof(line), f)) {
       if (memcmp(line, argv[2], len_key) == 0 && line[len_key] == ':') {
          /* overwrite value part */
          memcpy(&line[len_key+1], argv[3], len_val);
          len = len_key+1+len_val;
          line[len++] = '\n';
       } else {
          len = strlen(line);
       }
       fwrite(line, 1, len, stdout);
    }
    fclose(f);
    return 0;
}

As mentioned by Peter, it would probably better to use a script.