ifstream files

This is a discussion on ifstream files within the C++ Programming forums, part of the General Programming Boards category; Hi guys, I've been following Steve Heller's online book on C++ programming and have so far found it very useful. ...

  1. #1
    Registered User Stonehambey's Avatar
    Join Date
    Jan 2008
    Location
    Kent, UK
    Posts
    118

    ifstream files

    Hi guys,

    I've been following Steve Heller's online book on C++ programming and have so far found it very useful. However I have got stuck on a particular part of the book, and would really like some input from you guys

    Basically I'm learning about creating and using classes. In his example program Steve gradually builds a Stock Item program which uses a StockItem class to do various things. I've gotten to the point where the program reads the entries of stock from another file and puts them into a vector. It will probably be more useful if I post the source code for you It consists of three main files.

    Item2.h

    Code:
    class StockItem
    {
    public:
        StockItem();
    
        StockItem(std::string Name, short InStock, short Price, 
        std::string Distributor, std::string UPC);
    
        void Display();
        void Read(std::istream& is);
    
    private:
        short m_InStock;
        short m_Price;
        std::string m_Name;
        std::string m_Distributor;
        std::string m_UPC;
    };
    item2.cpp

    Code:
    #include <iostream>  
    #include <fstream>
    #include <string>
    #include "item2.h"
    using namespace std;
    
    StockItem::StockItem()
    : m_InStock(0), m_Price(0), m_Name(), 
      m_Distributor(), m_UPC()
    {
    }
    
    StockItem::StockItem(string Name, short InStock, 
    short Price, string Distributor, string UPC)
    : m_InStock(InStock), m_Price(Price), m_Name(Name), 
      m_Distributor(Distributor), m_UPC(UPC)
    {
    }
    
    void StockItem::Display()
    {
      cout << "Name: ";
      cout << m_Name << endl;
      cout << "Number in stock: ";
      cout << m_InStock << endl;
      cout << "Price: ";
      cout << m_Price << endl;
      cout << "Distributor: ";
      cout << m_Distributor << endl;
      cout << "UPC: ";
      cout << m_UPC << endl;
      cout << endl;
    }
    
    void StockItem::Read(istream& is)
    {
      getline(is,m_Name);
      is >> m_InStock;
      is >> m_Price;
      is.ignore();
      getline(is,m_Distributor);
      getline(is,m_UPC);
    }
    item2tst.cpp

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include "Vec.h"
    #include "ITEM2.h"
    
    using namespace std;
    
    int main()
    {
        ifstream ShopInfo("SHOP2.in");
        vector<StockItem> AllItems(100);
        short i;
        short InventoryCount;
    
        for (i = 0; i < 100; i ++)
            {
            AllItems[i].Read(ShopInfo);
            if (ShopInfo.fail() != 0)
                break;
            }
    
        InventoryCount = i;
    
        for (i = 0; i < InventoryCount; i ++)
            {
            AllItems[i].Display();
            }
    
        return 0;
    }
    Now my specific problem with this is the part where the program reads the "shop2.in" file. Firstly, I have never heard of an .in file and so I opened the program in notepad. It's basically a list of entries for the StockItem class. I'm using Microsoft Visual C++ to build the program and when I tried to import the shop2.in file it gave me an error/warning message telling me that it did not recognize the file type. I imported it anyway into the "Resource files" directory and ran the program (I later tried putting it in the source files and header files directories but was having the same problem)

    To my surprise the program compiled and linked without any errors. But when I went to run the program I was just presented with a blank screen.

    My guess is that the program wasn't reading the "shop2.in" file correctly and so the break command was triggering instantly (that is just my guess as a novice though).

    I'm at a bit of a loose end now trying to figure out how to make this work. Due to my pedantic nature I don't want to continue through the book until I'm able to make this program work.

    Many thanks for any help you can give me

    Kind Regards,

    Stonehambey

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,185
    Now my specific problem with this is the part where the program reads the "shop2.in" file. Firstly, I have never heard of an .in file and so I opened the program in notepad. It's basically a list of entries for the StockItem class. I'm using Microsoft Visual C++ to build the program and when I tried to import the shop2.in file it gave me an error/warning message telling me that it did not recognize the file type. I imported it anyway into the "Resource files" directory and ran the program (I later tried putting it in the source files and header files directories but was having the same problem)
    The file extension does not really matter here. You just need to copy the file to the place where the program would be run. You can rename it to "shop2.txt" if you prefer, but you will have to reflect that in the program source code since the filename is hard coded. As you have noticed, the program can be compiled even if the file cannot be found, but when you run the program, you may have a problem.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User Stonehambey's Avatar
    Join Date
    Jan 2008
    Location
    Kent, UK
    Posts
    118
    You just need to copy the file to the place where the program would be run.
    I'm having a little trouble understanding what you mean here, what do you mean by "the place where the program would be run"?

    Thanks,

    Stonehambey

    EDIT: I messed around a bit with it and put the exact directory path to the file, and it worked! Thanks for your help
    Last edited by Stonehambey; 03-04-2008 at 10:05 AM.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    The program opens a file from your hard disk, not your resource file.
    You should put the file in the directory where the actual program resides and it will find it. Otherwise you need to change the actual path in the program. You could tell it to look for another filename, of course.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    If you do not specify a path, the program grabs the file from the current working directory. In many cases that is where the application exe exists, but not always, so you may not want to rely on this behavior.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    I don't know if it is different with other operating systems, but unless you set a different working path in a shortcut before launching the app, the current directory is always the program path (also an exception when using development IDEs and debuggers).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    If you launch a program from a console, the console's working path is the program's working path. If you launch it through CreateProcess, you can give it an arbitrary working path.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    There are enough exceptions on Windows (and other OS's) that "always" is a bad term to use. We're up to four already.

  9. #9
    Registered User Stonehambey's Avatar
    Join Date
    Jan 2008
    Location
    Kent, UK
    Posts
    118
    Quote Originally Posted by Daved View Post
    If you do not specify a path, the program grabs the file from the current working directory. In many cases that is where the application exe exists, but not always, so you may not want to rely on this behavior.
    This is true. One of my initial attempts at a solution was to put the file in the same directory as the program, and in this case it still did not find it

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    Quote Originally Posted by Daved View Post
    There are enough exceptions on Windows (and other OS's) that "always" is a bad term to use. We're up to four already.
    Yes, unless there are exceptions, the default path is the program's directory. Perhaps that's a better term. The best thing to do it to set the working directory to the program's directory.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> Yes, unless there are exceptions, the default path is the program's directory.

    No, there is really no such thing as "default" since it depends on how you run the program and there is no "default" way to run an executable.

    If you want to say that the current working directory is often the same as the directory that contains the executable, that would be fine with me.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    I mean by default because if you don't specify a custom path to ShellExecute, CreateProcess or specify it in a shortcut, the working dir becomes the program dir.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Not true. If you are running from a command prompt, the working directory can also be different than the program directory. If you are executing from Visual Studio, the working directory can be different than program directory.

    It doesn't matter what term you use, as long as you present the information accurately. I'm just saying that "always" or "default" are inaccurate or at least misleading. If you say "often" or something else that indicates that there is a real possibility that the directories are different, then that is fine.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    Hehe. OK. To simplify it, the current working directory is often the program's directory.
    There are exceptions, however, so don't rely on it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    I would prefer, however, to supply "./" or no path, thus using the current directory, than supply the full path to a file. I hate it when programs hard code absolute paths. Also consider that some people -- myself included -- might change the current working directory in an attempt to get the program to read a file in a different directory.

    An alternative for Windows, if you want to use the directory that the executable is located in and not the current directory, is to use GetModuleFileName(). That gives you the absolute path to your executable, which you can then parse and extract the directory of, and add your filename to that. Again, however, it's not something I'd recommend, mostly for portability reasons.

    Finally, from my limited experience with Microsoft Visual C++, I think it puts your executable in a Debug/ or Release/ subdirectory of the main project directory, depending on which mode you compiled the program in. If your input file was therefore in the same directory as your source code, probably the main directory, this would not work. You could try using "../input.in" or copying/moving the input file to this subdirectory.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Create Copies of Files
    By Kanshu in forum C++ Programming
    Replies: 13
    Last Post: 05-09-2009, 08:53 AM
  2. Error opening files in a different dir
    By Ozzie in forum C++ Programming
    Replies: 3
    Last Post: 10-09-2008, 07:55 AM
  3. Working with muliple source files
    By Swarvy in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2008, 09:36 AM
  4. Program Deployment and DLL/OCX Files?
    By dfghjk in forum C++ Programming
    Replies: 5
    Last Post: 06-16-2008, 03:47 AM
  5. ofstream and ifstream for searching and writing
    By johnnyd in forum C++ Programming
    Replies: 6
    Last Post: 03-17-2003, 08:34 AM

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