read text file using c/c++

Posted on 2007-07-24
Last Modified: 2010-10-05
Hi All,
I have to read text file which has data in following manner,
2345  zxc  123344 abchfdfdfdg
I need to read fixed length and store same into variable,
Say first 6 character, then next 5 and so on&
This will also include spaces.

Whats the best way to do this??
Is fgetc is right way to do this?

Please suggest.

Thanks in advance.


Question by:vjabhi
    LVL 53

    Expert Comment

    Do a getline, and then process the line you got. Since you want to split it up at fixed indexes, that shouldn't be too hard ... substr should help :


    Don't forget to check out the example code at the bottom of those pages.

    For reading a file, check out this tutorial :

    LVL 39

    Accepted Solution

    You might use a structure that exactl ymatches the line:

    struct Record
         char sz1[6];
         char sz2[5];

    Then you could read like

         Record rec;
         ifstream ifs("data.txt");
         string line;
         while (getline(ifs, line))
               istringstream iss(line);
     *)&rec, sizeof(Record));
               if (!iss)
                   return;  // error
               rec.sz1[sizeof(rec.sz1)-1] = '\0'; // terminate string
               rec.sz2[sizeof(rec.sz2)-1] = '\0'; // terminate string
               v.push_back(rec);  // put record to an array

    Regards, Alex
    LVL 45

    Assisted Solution

    A third option is to use fscanf() to read the line a split the tokens.

    2345  zxc  123344 abchfdfdfdg
    I need to read fixed length and store same into variable,
    Say first 6 character, then next 5 and so on&

      char F1[7];   // size plus 1
      char F2[6];   // size plus 1
      char F3[8];   // size plus 1
      char F4[12]; // size plus 1

      fscanf (Input, "%6.6s%5.5s%8.8s%11.11s", F1, F2, F3, F4);

    Good Luck,

    LVL 1

    Expert Comment

    You could read 1 character at a time and loop through until you find what you want..

    #include <cstring>
    #include <fstream.h>
    using namespace std;

    string readCharacters(int charStart, int charEnd, char* filename)
       string ret;
       ifstream file (filename); // open file stream for reading using filename specified
       if ( !file.is_open() || !file.good() )
          // Error has occured opening file: Handle it.
          char c;
          for (int a = 0; a < charEnd; a++)
             c = (char)file.get(); // Get the character at this point in file
             if ( a > charStart && a < charEnd ) // if the character
                ret += c; // append character to string
       return ret;

    That is roughly how you could do it in C++, not sure if it works as I haven't tested it.
    You would use this function to get characters from charStart to charEnd in the file specified by filename.. i.e.

    string a = readCharacters(0,4,"C:\\file.txt");
    string b = readCharacters(5,8,"C:\\file.txt");
    LVL 3

    Expert Comment

    a simple program to read file line by line
            #include <stdio.h>
           #include <stdlib.h>

           int main(void)
                FILE * fp;
                char * line = NULL;
                size_t len = 0;
                ssize_t read;
                fp = fopen("file.txt", "r");
                if (fp == NULL)
                while ((read = getline(&line, &len, fp)) != -1) {
                     printf("Retrieved line of length %zu :\n", read);
                     printf("%s", line);
                if (line)
                return EXIT_SUCCESS;

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
    Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
    The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now