tags:

views:

261

answers:

5

After exhaustive googling and visiting many forums, I am yet to find a good comprehensive answer for this question. A lot of the forums suggest using the get line istream& getline (char* s, streamsize n ) function. My question is what if I don't know what the length of each line is and cannot predict what the size may be? Also what is it's equivalent in C?

Is there any specific function in c /c++ to read one single line each time from a text file ?

Explanation , with Code snippets will help me a lot.

+1  A: 

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();
Xorlev
Billy ONeal
How would we do it in C?
Eternal Learner
+2  A: 

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("filename.txt");
    std::string line;

    while( std::getline( input, line ) ) {
        std::cout<<line<<'\n';
    }

    return 0;
}

This program reads each line from a file and echos it to the console.

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

#include <stdio.h>

int main() {
    char line[1024];
    FILE *fp = fopen("filename.txt","r");

    if( fp == NULL ) {
        return 1;
    {

    while( fgets(line,1024,fp) ) {
        printf("%s\n",line);
    }

    return 0;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

Jacob
Thanks. How would we do the same in C? any tht's ?
Eternal Learner
Updated my post with how I recall doing it, I hope it is correct as I put it, otherwise I'll correct the post once people point out what I did wrong.
Jacob
Thanks, I was wondering if there was a better way than using a buffer of fixed length. I guess I now know that we need to hard code the buffer size .
Eternal Learner
I guess you could store the start position of a 'line' (Beginning of file or after new line), then scan through the file until you reach either the end of the line or the end of the file. Then take this position, find the difference in bytes from the first position, allocate a buffer large to hold this number of bytes, set the fp using fseek to the start of the line and read the data in to the buffer? I hope that made some sense.
Jacob
You could search for the end of line char '\n' and then allocate a buffer.
anno
A: 

In C, fgets(), and you need to know the maximum size to prevent truncation.

ninjalj
+4  A: 

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}
sje397
char c; ???!!!close(f) ?? and malloc.h!!! not stdlib.h
Nyan
@Nyan - cheers, fixed
sje397
A: 

Read c-faq.

Nyan