tags:

views:

119

answers:

6

I'm trying to output text from a file one line at a time. I'm currently hardcoding it and I have this so far:

int main(int argc, char *argv[])
{
    int x;
    int k;
    int limit = 5;
    FILE *file;

    file = fopen("C:\\Documents and Settings\\jon\\My Documents\\Visual Studio 2008\\Projects\\Project1\\Assignment8_2\\Debug\\TestFile1.txt", "r");
    if (file == NULL) {
     perror("Error");
    }

    for (k = 1; k <= limit; k++) {
     while ((x = fgetc(file)) != '\n') {
      printf("%c", x);
     }
    }
    fclose(file);
}

I was wondering where in the code above, if at all, I can check for EOF. I assume I need to do that, but not sure why. Still learning.... Thanks!

+2  A: 

Maybe you can try this:

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main() {
    int sum = 0;
    int x;
    ifstream inFile;

    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    while (inFile >> x) {
        sum = sum + x;
    }

    inFile.close();
    cout << "Sum = " << sum << endl; 
    return 0;
}
Ngu Soon Hui
+1 definitely c++ way of doing it, could use `ifstream in("filename"); if (!in.is_open()) return 0; ...`
stefanB
One line at a time, not an integer at a time.
DevSolar
A: 

you should check the eof from the output of fgetc:

...
x = fgetc(file);
while (x != '\n' && x != EOF) {
...

fgetc manual there

RageZ
One line at a time, not one character at a time.
DevSolar
and ? we are just checking for eof doesn't change anything ...
RageZ
A: 

Smells like homework... check some of the many, many tutorials online. for example

beggs
You can always ignore a question :-) He is doing his homework proactively, though, by asking questions.
Rob Vermeulen
I should be more genital then :-) "smells like homework, but as you've gotten most of the way already, and shown your work, check out some of the **many, many** tutorials online... they explain it quite well" :-)
beggs
+5  A: 

If you can bound the maximum length of a line, fgets may be a better way to read each line; but since you mention C++, you might consider using, instead, getline (caveat: fgets also put the \n in the buffer it fills, getline doesn't). Both make easy to check for end of file (fgets returns NULL on eof, getline sets the eofbit on its istream argument, which it also returns).

Alex Martelli
+2  A: 

fgets() for C, getline() for C++.

C:

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

// adjust as appropriate
size_t const MAX_LINE_LENGTH = 1024;

int main()
{
    FILE * in;
    char line[ MAX_LINE_LENGTH ];
    if ( ( in = fopen( "test.txt", "r" ) ) == NULL )
    {
        puts( "Failed to open test.txt." );
        return EXIT_FAILURE;
    }
    while ( fgets( line, MAX_LINE_LENGTH, in ) != NULL )
    {
        printf( "%s", line );
    }
    fclose( in );
    return EXIT_SUCCESS;
}

C++:

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

int main()
{
    std::ifstream in( "test.txt" );
    std::string line;
    while ( getline( in, line ) )
    {
        std::cout << line << std::endl;
    }
    in.close();
    return 0;
}
DevSolar
No need to explicitly call close() unless you want to check for errors or catch and handle exceptions. Otherwise just let RAII do its magic.
Martin York
Not *necessary*, but good style IMHO. If used in a larger function, it marks clearly that `in` has been dealt with and will not be used anymore. Call me anal retentive if you like. ;-)
DevSolar
+1 for the clean C++ example. It's the tidiest example in this thread.I'd omit the close() call, though. It is redundant, therefore boiler plate. RAII should work just fine here.
Rob Vermeulen
A: 

you can call feof() to check for EOF or check if the return code for fgetc() matches EOF.

I'm adding both versions to your code although I'm not sure what the loops (especially the outer one) are supposed to do, but within the context of your sample, EOF checking would look like this..

/* EOF would now terminate both loops, using feof() and fgetc() return to check EOF */ 
for (k = 1; k <= limit && !feof(file); k++) {
    while ((x = fgetc(file))!='\n' && x!=EOF) {
            printf("%c", x);
    }
}
Nicholaz