Thread: Passing filename as a string

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    12

    Passing filename as a string

    Hi, me again!

    I have this code:

    Code:
    char* getfilebits(char* filename)
    {
    	char* ptr;
    	ifstream file (filename, ios::in|ios::binary); // open file for reading
    	if (file.is_open()) // did it open?
    	{
    		ptr=new char[16]; // make space for data
    		file.read(ptr, 16); //read data from file
    		file.close(); // close file, it is needed no longer
    		//return 0;
    	}else{
    		cout << "Could not open file" << endl;
    		terminate();
    	};
    	return ptr;
    };
    It works, but the fact that I need to take filename as a char* bugs me. Is there any way to get ifstream to accept a string as a file name?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    Code:
    char* getfilebits(const std::string& filename)
    {
    	char* ptr;
    	ifstream file (filename.c_str(), ios::in|ios::binary); // open file for reading
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    12
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. Passing an array into a function
    By Ryston in forum C++ Programming
    Replies: 4
    Last Post: 08-29-2006, 05:20 AM
  3. Passing an 8-bit String
    By slowcoder in forum C Programming
    Replies: 8
    Last Post: 08-01-2006, 07:18 AM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  5. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM