[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

read text file using c/c++

Posted on 2007-07-24
6
Medium Priority
?
2,737 Views
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.

Thanks,
Abhi



0
Comment
Question by:vjabhi
5 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 19554034
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 :

        http://www.cplusplus.com/reference/string/getline.html
        http://www.cplusplus.com/reference/string/string/substr.html

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

For reading a file, check out this tutorial :

        http://www.cplusplus.com/doc/tutorial/files.html
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 100 total points
ID: 19554193
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);
           iss.read((char*)&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
0
 
LVL 46

Assisted Solution

by:Kent Olsen
Kent Olsen earned 100 total points
ID: 19555428
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,
Kent

0
 
LVL 1

Expert Comment

by:henderbops
ID: 19591780
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.
   }
   else
   }
      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
         }
      }
   }
   file.close();
   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");
etc
0
 
LVL 3

Expert Comment

by:aatrish2001
ID: 19606464
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)
                 exit(EXIT_FAILURE);
            while ((read = getline(&line, &len, fp)) != -1) {
                 printf("Retrieved line of length %zu :\n", read);
                 printf("%s", line);
            }
            if (line)
                 free(line);
            return EXIT_SUCCESS;
       }
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

873 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