Help on opening files

This is a discussion on Help on opening files within the C++ Programming forums, part of the General Programming Boards category; Ok, I am just starting to play with C++ and have written a class that opens files for practice. Does ...

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    51

    Help on opening files

    Ok, I am just starting to play with C++ and have written a class that opens files for practice. Does anyone know why this is not opening the files? (or if it is, why it is not exiting) I am sending it basic input like c:\test.txt (and using a file that i do have in my c:\).

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    class myFileLoader
    {
    	public:
    		void getName();
    
    	private:
    		FILE *itsName;
    };
    
    void myFileLoader::getName()
    {
    	FILE *temp;
    	
    	char str[100];
    	
    	printf("Please enter the file you wish to load:  ");
    	fgets(str, 99, stdin);
    	
    	while ((temp = fopen(str, "r")) == NULL )
    	{
    		printf("\n******File was not opened, Please try again******");
    		printf("\nPlease enter the file you wish to load:  ");
    		fgets(str, 99, stdin);
    	}
    	printf("\nFile sucessfully loaded!");
    
    	itsName = temp;
    
    }
    
    
    int main()
    {
    	myFileLoader test;
    
    	test.getName();
    	
    	return 0;
    }
    Also, if I wanted to put the class in a header file and its function in another cpp file and include it all together, would I need to use #IFNDEFINE and call the other <stdio.h> so that they would know what FILE is supposed to be?

    P.S. any pointers on the code would be appreciated.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    I think fgets() retains the newline character at the end, so:

    > fgets(str, 99, stdin);
    str[strlen(str)-1] = '\0'; //lose the newline

    For strlen(), add this at the top:
    #include <cstring>
    using namespace std;

    As to your other question, I think yes, you would need to include <stdio.h> in the cpp file with the class functions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Opening ASCII files in C?
    By Mavix in forum C Programming
    Replies: 6
    Last Post: 04-25-2007, 03:23 PM
  2. Need help opening a series of files
    By ramparts in forum C Programming
    Replies: 9
    Last Post: 11-14-2006, 05:49 PM
  3. Opening files with UNICODE file names
    By decohk in forum Linux Programming
    Replies: 2
    Last Post: 11-09-2006, 05:25 AM
  4. opening files
    By angelic79 in forum C Programming
    Replies: 3
    Last Post: 10-19-2004, 07:52 AM
  5. Opening files - Giving options?
    By wwwGazUKcom in forum C++ Programming
    Replies: 3
    Last Post: 09-18-2001, 08:06 AM

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