Thread: Read text file line by line and write lines to other files

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    6

    Read text file line by line and write lines to other files

    Hello,
    How can read the file /var/etc/allInOne.cfg and split it into mltiple cfg files.

    the source file "/var/etc/allInOne.cfg "look like this:

    line1
    line2
    ...
    line10
    filePath:/var/etc/file1.cfg
    line12
    line13
    ...
    line14
    filePath:/var/etc/file2.cfg
    linen
    ..
    filePath:/var/etc/filen.cfg

    Code:
    void genCfg(int err)
    {
    // create a buffer to read the allInOne.cfg.
    char buf[512];
    char linesbuf[2048];;
    // declare the variables we will use in this function
    // open temporary file cotaining the data 
    FILE *f = fopen("/var/etc/allInOne.cfg", "rt");
    if (f)
    {
     while (fgets(buf, 512, f)
     {
     // if we found this string the we can stop to read and create the cfg file then continue the read
     if (strstr(buf, "filePath:")) {
                                    FILE *fp;
                                    fp = fopen(buf,"w"); //the buf contain the path and filename
                                    /*Create a file and add text*/
                                    printf(fp,"%s",lines); /*writes data to the file*/
                                    fclose(fp); /*done!*/
                                    lines = ""; initialize lines for next cfg file
     }
     else 
      //store the line in the variable		       
      lines += buf;
    }
    // close file
    fclose(f);
    return 0
    }
    }
    Last edited by magische_vogel; 01-22-2011 at 11:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  2. Line Counting
    By 00Sven in forum C Programming
    Replies: 26
    Last Post: 04-02-2006, 08:59 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM