C++ File Read help

This is a discussion on C++ File Read help within the C++ Programming forums, part of the General Programming Boards category; Hey, First of all, I am not a great programmer and lately I have not been having the best of ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    24

    C++ File Read help

    Hey,

    First of all, I am not a great programmer and lately I have not been having the best of luck getting my code to work (go figure!). Hopefully one of you will be able to help me out...

    I wrote this code to open a txt file and print it to a screen, just to make sure it was opening the file in the first place. Once that is working, I need to take the variables from each line (5 in total, 3 char's and 2 int's). My question is, is there any reason that this code would not work? The program doesn't seem to do anything:

    Code:
    int main()
    {
    	// ifstream constructor opens the file
    	char buffer[256];
    	
    	ifstream Conductor( "tblConductor.txt" );
    
    	if ( ! Conductor.is_open() ) {
    		cout << "ERROR - File could not be opened\n";
    		exit(1);
    	}
    	
    	while ( ! Conductor.eof() ) {
    		Conductor.getline(buffer, 100);
    		cout << buffer << endl;
    		cin.ignore();
    	}
    
    	return 0;
    }
    Also, I can not find any help for how to read in each of the lines of the tblConductor.txt file and assign the info to a variable in C++. Thanks in advance for your help.

  2. #2
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    try somethign more along these lines:
    Code:
    #include<iostream>
    #include<fstream>
    
    using std::ifstream;
    using std::cout;
    using std::endl;
    using std::cin;
    
    int main()
    {
    	ifstream infile("yourfile.txt");	//open the file
    	char line[128];	//create a char array
    
    	if(!infile.is_open())
    		cout<<"The File Flags are not OK";
    	else
    	{
    		while(!infile.eof())
    		{
    			infile.getline(line,1287,'\n');
    			cout<<line<<endl;
    		}
    	}
    
    	cin.get();
    	return 0;
    }
    note: this code hasn't been tested...

    and you do know how to take in a variable from a text file... you're doing it already...
    Last edited by major_small; 06-03-2004 at 11:11 AM. Reason: one little char can ruin a program
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    Try this:
    Code:
    int main()
    {
    	// ifstream constructor opens the file
    	char buffer[256];
    	
    	ifstream Conductor( "tblConductor.txt" );
    
    	if ( ! Conductor.is_open() ) {
    		cout << "ERROR - File could not be opened\n";
    		exit(1);
    	}
    	
    	while ( ! Conductor.eof() ) {
    //		Conductor.getline(buffer, 100);
    		/* Let getline find the end of line.
    		Just ensure you don't overflow your buffer */
    
    		Conductor.getline(buffer, 255);
    		cout << buffer << endl;
    //		cin.ignore();  //You don't need this
    	}
    
    	return 0;
    }
    Also, I can not find any help for how to read in each of the lines of the tblConductor.txt file and assign the info to a variable in C++.
    Your getline call reads in a line of data from the file and assigns it to a variable.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    24
    Thanks for your help, but this still does not do anything. I am starting to wonder if there is something wrong with the txt file. Basically, this is the content and format of the txt file:

    344,"8-28.17","8-28.15","750MCM","No rating",0
    345,"8-28.17","8-28.16","477AL","No cable rating.",0
    347,"8-28.18","8-28.13","750MCM","No rating.",0

    Each variable is seperated by a comma. Is there a way to modify my code to read each line into C++ and assign each variable a different name (not just line)?

    Once again, thanks for all your help...this board has been a life saver!

  5. #5
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    yes, use getline, just don't use the endline character as the terminator... for example, change this
    Code:
    infile.getline(line,128,'\n');
    to this
    Code:
    infile.getline(line,128,',');
    and for the integers, just use
    Code:
    infile>>intNumber>>floatNumber;
    to clarify, in this case, you can pretty much use the filestream the same way you've been using the istream...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  6. #6
    Registered User
    Join Date
    Jun 2004
    Posts
    24
    Again guys, I can't thank you enough for your help. I tried to modify my original code to real a random access file as follows:

    Code:
    // Reading data from a text file exported from Access
    
    #include <iostream.h>
    #include <iomanip.h>
    #include <fstream.h>
    #include <stdlib.h>
    #include "read.h"
    
    void outputLine( ostream&, const FileData & );
    
    int main()
    {
    	// ifstream constructor opens the file
    	
    	ifstream Conductor( "tblConductor2.txt", ios::in );
    
    	if ( ! Conductor.is_open() ) {
    		cerr << "ERROR - File could not be opened\n";
    		exit(1);
    	}
    
    	cout << setiosflags( ios::left ) << setw( 12 ) << "Conductor" << setw( 12 ) << "Line"
    		 << setw( 12 ) << "Number1" << setw( 20 ) << "Number2" << endl;
    	
    
    	FileData file;
    
    	Conductor.read( reinterpret_cast<char*>( &file ), sizeof ( FileData ) );
    
    	while ( Conductor && !Conductor.eof() ) {
    		if ( file.conductor != 0 )
    			outputLine( cout, file );
    
    		Conductor.read( reinterpret_cast<char *>( &file ), sizeof( FileData ) );
    	return 0;								
    }
    
    void outputLine( ostream &output, const FileData &f )
    {
    	output << setiosflags( ios::left ) << setw( 12 ) << f.conductor << setw( 12 ) << f.line
    		 << setw( 12 ) << f.number1 << setw( 20 ) << f.number2 << '\n';
    }
    Here's the header file:
    Code:
    // Header file for ReadFile.cpp
    
    #ifndef READ_H
    #define READ_H
    
    struct FileData {
    	int line;
    	char conductor [ 30 ];
    	float number1, number2;
    };
    
    #endif
    I am getting an error that my function outputLine "local function definitions are illegal" and that also the program ReadFile.cpp "end of file found before the left brace". I have no idea how to de-bug either of these.

    Any ideas?

    Thanks again!!

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > while ( Conductor && !Conductor.eof() ) {
    Well you need a right brace for this while loop.

  8. #8
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > ifstream Conductor( "tblConductor2.txt", ios::in );

    Also, if it's a random access file, you need to open the file in binary mode. Either:
    ifstream Conductor( "tblConductor2.txt", ios::in | ios::binary );
    Or even easier:
    ifstream Conductor( "tblConductor2.txt", ios::binary );

  9. #9
    Registered User
    Join Date
    Jun 2004
    Posts
    24
    Thanks for your comments...it seems that it's always some small reason why the program doesn't compile (like missing a "}" in this case).

    Now that it has compiled, it still doesn't seem to work. I am stepping through my program but the following logic test seems to come up false:
    Code:
    "while ( Conductor && !Conductor.eof() ) {... "
    I tried to change it to the following with the same result:
    Code:
    "while ( Conductor.eof() ) {..."
    So, now I think that the program doesn't like my file. So, finally, I just changed the while loop to the following to see what's happening:
    Code:
    "while (1) {..."
    The result is a bunch of unformatted output. For example, the first thing I'm trying to get out of the text file is a char. But all that comes out on the screen is a bunch of symbols that mean nothing.

    Any advice on how to format the output? The data is totally useless the way it is.

    Thanks for all the tips so far...please be patient, I'm getting there!

  10. #10
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    If the file you are reading from wasn't written with write() you may have a problem reading it with read(). You might try doing something like this:
    Code:
    Conductor >> file.line;
    cout << file.line << endl; //debugging code 
     
    //if line is there, assume the rest of a file is too
    while(Conductor)
    {
      Conductor >> file.conductor;
      cout << file.conductor << endl;  //debugging
      
      Conductor >> file.number1;
      cout << file.number1 << endl;  //debugging
      
      Conductor >> file.number2;
      cout << file.number1 << endl; //debugging
     
      //if conductor string is not empty, send file to storage
      if(strcmp(file.conductor, 0) != 0)
    	outputLine(cout, file);
     
     Conductor >> file.line;
     cout << file.line << endl; //debugging
    }
    Then if you don't get what you're expecting you'll know where the problem is, rather than trying to black box it with read().

    Note: you were trying to use != on a C style string-----won't work. Whether that was the entire problem or not, can't say.

  11. #11
    Registered User
    Join Date
    Jun 2004
    Posts
    24


    I am still having difficulty with this read file thing. I tried all the suggestions in this thread, but nothing seems to work. So, I'll try explaining the problem again:

    What I am trying to do is read four variables per line from a text file that was exported from Access. Each line contains a char (conductor), an integer (line), and two floats (number1 & number2). The code that I have written below seems to read the data, but the output is meaningless, unformatted data. Instead of getting the conductor name out of the file (which should be "8-28.17"), I get a bunch of characters that mean nothing, followed by a long negative integer and two very large float numbers; all of which are not equal to what is written in the text file. I tried removing the function "read" as suggested above, but the results were the same. I am open to any suggestions that you may have, since I seem to be spinning my wheels on this one.

    It compiles fine, but when I run the code, I get the following error:
    Code:
    'Read File.exe': Loaded 'C:\WINNT\system32\NTDLL.DLL', Cannot find or open a required DBG file.
    'Read File.exe': Loaded 'C:\WINNT\system32\KERNEL32.DLL', Cannot find or open a required DBG file.
    The program '[1252] Read File.exe: Native' has exited with code 0 (0x0).
    So, as it stands, here is the code that I am using (but is not working yet):

    Code:
    // Reading data from a text file exported from Access
    
    #include <iostream.h>
    #include <iomanip.h>
    #include <fstream.h>
    #include <stdlib.h>
    #include "read.h"
    
    void outputLine( const FileData & );
    
    int main()
    {
    	// ifstream constructor opens the file
    	
    	ifstream Conductor( "tblConductor.txt", ios::in );
    
    	if ( ! Conductor.is_open() ) {
    		cerr << "ERROR - File could not be opened\n";
    		exit(1);
    	}
    
    	cout << setiosflags( ios::left ) << setw( 12 ) << "Conductor" << setw( 12 ) << "Line"
    		 << setw( 12 ) << "Number1" << setw( 20 ) << "Number2" << endl;
    	
    	FileData file;
    
    	Conductor.read( reinterpret_cast<char*>( &file ), sizeof ( FileData ) );
    	
    	while ( Conductor ) {
    		outputLine( file );
    		Conductor.read( reinterpret_cast<char *>( &file ), sizeof( FileData ) );
    	}
        	
    	return 0;								// ifstream constructor closes the file
    }
    
    void outputLine( const FileData &f )
    {
    	cout << setiosflags( ios::left ) << setw( 12 ) << f.cond << setw( 12 ) << f.line
    		 << setw( 12 ) << f.number1 << setw( 20 ) << f.number2 << '\n';
    }
    Here is the content of the text file for those interested:
    Code:
    "#2"		0	130.00	170.00
    "#2ACSR"		0	160.00	230.00
    Here is my "read.h" file:
    Code:
    // Header file for ReadFile.cpp
    
    #ifndef READ_H
    #define READ_H
    
    struct FileData {
    	int line;
    	char cond [ 30 ];
    	float number1, number2;
    };
    
    #endif
    Also, one other question, could the size of my cond array above be the problem?
    Thanks!!

  12. #12
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >>Here is the content of the text file for those interested:

    If you open tblConductor2.txt file in a simple text editor like Notepad do you see the table as posted?
    Last edited by elad; 06-09-2004 at 04:45 PM.

  13. #13
    Registered User
    Join Date
    Jun 2004
    Posts
    24
    Yes, the file appears as posted.

  14. #14
    Registered User
    Join Date
    Jun 2004
    Posts
    24
    Would it make a difference if the file was in the following format instead?

    Code:
    344,"8-28.17","8-28.15","750MCM","No rating",0
    345,"8-28.17","8-28.16","477AL","No cable rating.",0
    347,"8-28.18","8-28.13","750MCM","No rating.",0
    This is another file that I have to input once I figure out this one. This file is csv with int, char, char, char, char, int.

  15. #15
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Instead of getting the conductor name out of the file (which should be "8-28.17"),

    The file you posted doesn't show 8-28-17
    Code:
    "#2"		0	130.00	170.00
    "#2ACSR"		0	160.00	230.00
    But irregardless, this looks like a text file. Conductor.read() only works for binary files, not text files. You should use something like:

    Conductor >> conductor >> line >> number1 >> number2;

    Look at Elad's code above. His code should work. Alternalely, you could read in a line at at time with getline(), then parse the line.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 01:36 PM
  2. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 05:54 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 04:39 AM
  4. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21