Passing filename as a string

This is a discussion on Passing filename as a string within the C++ Programming forums, part of the General Programming Boards category; Hi, me again! I have this code: Code: char* getfilebits(char* filename) { char* ptr; ifstream file (filename, ios::in|ios::binary); // open ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,457
    Code:
    char* getfilebits(const std::string& filename)
    {
    	char* ptr;
    	ifstream file (filename.c_str(), ios::in|ios::binary); // open file for reading
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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

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