i/o stuff

This is a discussion on i/o stuff within the C++ Programming forums, part of the General Programming Boards category; I'm trying to read a file I text file I created in notepad. Can it read notepad files? Does the ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    465

    i/o stuff

    I'm trying to read a file I text file I created in notepad. Can it read notepad files? Does the file have to be in a certain place in order for the program to find it?
    My code:
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        char str[100];
        
        ifstream a_file ("hi.txt");
        a_file>>str;
        cout<<str<<"/n";
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    My result:
    α╒w< "/nPress any key to continue . . .

    Whats wrong? How do I fix it?
    My computer is awesome.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,546
    Well I'd say it never opened the file at all, and what you're seeing is the random junk which was in str right at the start of the program.

    Either make sure the file is in the directory which the program thinks is the current directory, or specify an absolute path to the file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    notepad creates simple text files (I believe) and so a simple program like yours should be able to open and read the data contained within.

    Quote Originally Posted by cerin
    Whats wrong?
    At least three things.

    1) "/n" should be "\n" I'm guessing.
    2) You never test whether the file was opened or not... if not, then the output you provided could be the result of random data present in the array.
    3) You should probably use one of the get or read member functions provided by the ifstream object to make sure you aren't getting more data than your program (the array) can handle.

    Beyond that, what does the file look like when you open it in notepad?
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    All my file says in notepad is:

    hi
    hi
    hi
    hi
    hi
    hi
    My computer is awesome.

  5. #5
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    First make surethe file has opened properly by checking the fail() method:
    Code:
    std::ifstream file("myfile.txt");
    if(file.fail()) return 0;
    Then to read a word from the file:
    Code:
    std::string word;
    file >> word;
    Or to read a line from the file:
    Code:
    std::string line;
    std::getline(file, line);
    Or to read the entire file:
    Code:
    //Get size of file
    file.seekg(0, std::ios::end);
    int size = file.tellg();
    char* buffer = new char[size + 1];
    
    //Read from file
    file.seekg(0, std::ios::beg);
    file.read(buffer, size);
    
    //End string with NULL terminator, just in case...
    buffer[size] = '\0';
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  6. #6
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    Will this work for checking if the file is open?
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        char str[100];
        
        ifstream a_file ("hi.txt");
        if (!a_file.is_open()){
        cout<<"File isn't open.";
        }
        else{
        a_file>>str;
        cout<<str<<"/n";
        }
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    Edit: forgot curly brace after cout
    Last edited by cerin; 02-14-2005 at 04:17 PM.
    My computer is awesome.

  7. #7
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    This is my new code:
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        char str[100];
        
        ifstream a_file ("hi.txt");
        if (!a_file.is_open()){
        cout<<"File isn't open.";
        }
        else{
        a_file>>str;
        cout<<str<<"\n";
        }
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    Is there any easy way to read the entire file than the one below? So I only have to change a few things?? Or at least a couple lines instead of one?

    Code:
    //Get size of file
    file.seekg(0, std::ios::end);
    int size = file.tellg();
    char* buffer = new char[size + 1];
    
    //Read from file
    file.seekg(0, std::ios::beg);
    file.read(buffer, size);
    
    //End string with NULL terminator, just in case...
    buffer[size] = '\0';
    My computer is awesome.

  8. #8
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Is there any easy way to read the entire file than the one below?
    Not with >> operator. That operator is for reading what's called 'formatted' input. What that means is the >> operator takes certain predefined actions when it comes across whitespace(spaces, tabs, newlines) in your input file. One of the predefined actions the operator >> takes is to stop reading data when it encounters trailing whitespace, e.g a space or a newline character('\n'). The >> operator is also defined to skip any leading whitespace. So, if the >> operator is reading a line in your file it keeps reading characters until it comes to a whitespace character and then stops. The next time the >> operator is called, it skips leading whitespace until it finds some characters, and then it reads in characters until it comes to another whitespace. In that manner, the >> operator is said to treat the data in the input file as 'formatted' data, i.e. the data is formatted as words.

    If you use the get() and getline() functions, you can read in different amounts of input, and they treat the input file as 'unformatted' input. As a practical matter, that just means the get() and getline() functions have different rules on how much input they will read in. Generally, the way it works is they treat whitespace just like any other character, so whitespace does not necessarily cause reading to stop( as it will with the >> operator).

    The designation 'unformatted' or 'formatted' input doesn't mean the input file looks any different. For instance, this data

    apple pear cherry

    can be either formatted input or unformatted input--it just depends on whether you are using the >> operator which reads in input one word at a time, or you are using the get() functions which treat the data as one continuous string of characters.

    In your program, you could use the getline() function for a string:

    string str;
    getline(inFile, str);

    The getline() function has a third parameter which indicates the 'delimiter'. A 'delimiter' tells the function when to stop reading data. The default value is '\n'. So, the function above will stop reading characters into the string str when it comes upon a '\n' character. However, you can set that delimiter to anything you want:

    string str;
    getline(inFile, str, '#');

    I that case, getline() will continue reading characters from the file until the '#' character is encountered--even across multiple lines. You can put the character at the end of the file, and getline() will read the whole file into the string str.
    Last edited by 7stud; 02-15-2005 at 11:56 PM.

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Quote Originally Posted by cerin
    Is there any easy way to read the entire file than the one below? So I only have to change a few things?? Or at least a couple lines instead of one?
    If you are simply trying to store the entire contents of a text file in a mass buffer of some kind in as few steps as possible then there are at least a couple of options for you:

    You could store everything in a string:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <algorithm>
    #include <iterator>
    
    int main()
    {
        std::string str;
        std::ifstream input("hi.txt");
    
        // Read entire file into string container...
        input.unsetf(std::ios::skipws);  // Preserve/store whitespace characters
        std::copy(std::istream_iterator<char>(input),std::istream_iterator<char>(),
                  std::inserter(str,str.end()));
    
        // Output file contents to cout...
        std::cout << str << std::endl;
    
    }

    You can also use a stringstream:
    Code:
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    
    int main()
    {
        std::stringstream str;
        std::ifstream input("hi.txt");
    
        // Read entire file into stringstream...
        str << input.rdbuf();
    
        // Output file contents to cout...
        std::cout << str.str() << std::endl;
    
    }
    Given a file hi.txt containing the following:
    Code:
    hi there
    hi there
    hi there
    hi there
    Then of course the output should be:
    Code:
    hi there
    hi there
    hi there
    hi there
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  10. #10
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    How do I make it display the text that the program read? could you fit it into the code Magos gave me plz?
    My computer is awesome.

  11. #11
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Have you gotten anything to work?

    If you are using windows, you will need to do something like this to the file name:

    fstream inFile("C:\\Beginning C++\\data.txt");

    You can read in some data and output it doing something like this:

    string str;
    inFile>>str;
    cout<<str<<endl;

    As I explained in my previous post, that will read in one word. I also explained in my previous post how you can read in the whole file.

  12. #12
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    This is my code:
    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        char str[100];
        
        ifstream a_file("hi.txt");
    a_file.seekg(0, std::ios::end);
    int size = a_file.tellg();
    char* buffer = new char[size + 1];
    
    //Read from file
    a_file.seekg(0, std::ios::beg);
    a_file.read(buffer, size);
    
    
    //End string with NULL terminator, just in case...
    buffer[size] = '\0';
    
    
    
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    Sorry, but I don't want to know how to read 1 word or line.
    It reads the file, but how do I get it to display it?
    My computer is awesome.

  13. #13
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Have you been introduced to cout yet? It's usually one of the first things you learn--otherwise you couldn't run programs that displayed anything. Use cout to display the variable with the data in it. Or, do you not know which variable has the data in it? If you don't understand the code you posted, maybe you should use a simpler method as outlined at the end of my previous post.
    Last edited by 7stud; 02-16-2005 at 05:45 PM.

  14. #14
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    Yes I've been introduced to cout. I don't understand what variable.

    I put in:
    Code:
    cout<<a_file;
    It diplays 0.
    I put it right below
    Code:
    a_file.read(buffer, size);
    My computer is awesome.

  15. #15
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Well, according to the code you just brute force copy and pasted the pointer containing the data you read is called buffer. May I refer you to your code:
    a_file.read(buffer, size);
    That statement reads size bytes into buffer. Cerin, is this a language barrier problem or do you not understand the code?
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Raw I/O vs. Stream I/O
    By NuNn in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 08:32 AM
  2. quick file i/o
    By breanne in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 08-12-2002, 03:29 PM
  3. Your stuff
    By smog890 in forum C Programming
    Replies: 6
    Last Post: 06-13-2002, 11:50 PM
  4. Linked lists and file i/o, and some other stuff
    By ninja in forum C++ Programming
    Replies: 9
    Last Post: 05-19-2002, 07:15 PM
  5. WSAAsyncSelect I/O Mode :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 1
    Last Post: 05-12-2002, 03:23 PM

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