Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 558883
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T12:10:44+00:00 2026-05-13T12:10:44+00:00

In C++, you can use non-member getline() with a stream in a loop like

  • 0

In C++, you can use non-member getline() with a stream in a loop like this:

#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;

int main() {
    ifstream in("file.txt");
    if (!in) {
        return EXIT_FAILURE;
    }
    for (string line; getline(in, line); ) {
        // Do stuff with each line
    }
}

However, I want to do that with a FILE* created by _wfopen(“file.txt”, “r”) instead, so I created one:

#include <cstdio>
#include <string>
#include <cstdlib>
#include <cwchar>
using namespace std;

bool getline(FILE* const in, string& s) {
    int c = fgetc(in);
    if (c == EOF) {
        return false;
    }
    s.clear();
    while (c != EOF && c != 10 && c != 13) {
        s += c;
        c = fgetc(in);
    }
    return true;
}

int main() {
    FILE* const in = _wfopen(L"file.txt", L"r");
    if (!in) {
        return EXIT_FAILURE;
    }
    for (string line; getline(in, line); ) {
        // Do stuff with the line
    }
    if (in) {
        fclose(in);
    }
}

It handles newlines like I want and works in a loop like I want. It’s just too slow because I’m reading one char at a time and inserting one char in the string at a time. For example, it takes 6 seconds to process a 12MB file while the original getline does it virtually instantly. That’s not that big of a deal for a small file, but for a 2GB file for example, it’d be a problem.

I’d like it to be as fast as C++’s getline(), but I don’t think I can make it any faster without redesigning it.

So, how should I redesign it so it’s more efficient?

I know I should fread in chunks into a buffer (a vector for example and resize when needed) till I find() a newline or newline pair in it and append the range to the string. However, I’m not really picturing how to make it work like my char-by-char version, especially if I read in too much and have to put data after the newline or newline pair back into the stream so it can be consumed on the next iteration.

Now, VC++ has a wifstream that takes a FILE* and STLPort might have one too. But, I’m using just Mingw 4.4.1. (I don’t want to use STLPort because it’s a pain in the ass to build with Mingw.)

The reason I need to use a FILE* is because that’s what _wfopen() returns. I need to use _wfopen() because it supports wchar_t* paths that I will be getting from the wchar_t** array returned by windows function CommandLineToArgvW(CommandLineW(), &argc). ifstream doesn’t take a wide path.

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T12:10:44+00:00Added an answer on May 13, 2026 at 12:10 pm

    You should be using C++ I/O facilities if you’re programming in C++. Having said that…

    First, you are checking for newline by checking for 10 and 13. You should open your file in text mode, and check for '\n' instead. This method is portable, and works with different line-end conventions, as well as on non-ASCII systems.

    Assuming you have to use native C FILE *, I would do it this way:

    #include <cstdio>
    #include <cstring>
    #include <string>
    
    bool cgetline(FILE* const in, std::string &s)
    {
        char buf[BUFSIZ+1] = {0};
        s.clear();
        while (fgets(buf, sizeof buf, in) != NULL) {
            char *end = strchr(buf, '\n');
            if (end == NULL) {
                /* We didn't see a newline at the end of the line,
                   if we hit the end of file, then the last line wasn't terminated
                   with a newline character.  Return it anyway. */
                if (feof(in)) {
                    s.append(buf, strlen(buf));
                    return true;
                } else {
                    s.append(buf, sizeof buf - 1);
                }
            } else {
                s.append(buf, end - buf);
                return true;
            }
        }
        return false;
    }
    

    The complication is from making sure the program does the right thing when the last line of a file doesn’t end with a newline character.

    Reading from a file character-by-character and appending to a string is probably why your version is slow.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is their a way to use a non-member non-friend function on an object using
In C#, if I want to deterministically clean up non-managed resources, I can use
We have a SQL server database. To manipulate the data non-programmatically, I can use
You can use SelectFolder() to get a folder or GetOpenFolderitem(filter as string) to get
I'm trying to use partial template specialization on a (non-member) function, and I'm tripping
You can use more than one css class in an HTML tag in current
You can use a standard dot notation or a method call in Objective-C to
I can use properties of an Excel Worksheet to tell if the worksheet is
You can use ftplib for full FTP support in Python. However the preferred way
You can use App.config; but it only supports key/value pairs. You can use .Net

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.