#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0

    Problems with passing a string


    I have this main function which passes the name of a file to be opened.

    Code:
    main() 
    {     
    char inputName[20] = "index.txt";     
     printWords(inputName); 
    }
    Then this is the code which is to open the file - but I always get an error saying the file doesn't exist.

    Code:
    void printWords(char *test) 
    {     
    FILE * fr; 	  	
    fr = fopen (test, "r");

    And if I do this... it works.

    Code:
    void printWords(char *test)
    {    
     FILE * fr; 	 	
    char fileName[20] = "input.txt";  	
    fr = fopen (fileName, "r");
    Could you explain to me why?

    Thanks for the help :)
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    98
    Rep Power
    3
    A few issues.

    Try:
    Code:
    void printWords(char test[]) 
    {     
    FILE * fr; 	  	
    char buffer[100];
    fr = fopen (test, "r");
    	while (! feof(fr) ) {
    		if ( fgets (buffer , 100 , fr) == NULL ) break;
           fputs (buffer , stdout);
    	}
    }
    
    int main() 
    {     
    char inputName[10] = "index.txt";     
     printWords(inputName); 
    
    }
    This works because the function printWords parameter was correctly declared as an array with char test[]. This means a pointer to the array test. You can pass arrays with this declared as a parameter of your function:

    Code:
    datatype arrName[]
    Also, you assigned an index that was too large for your array. The index.txt is only 9 characters.

    Then I tested for the end of file, and while that condition is false read the lines into buffer and print them.

    Oh yeah. Make sure index.txt is in the programs root directory, lol.
    Last edited by BitZoid; March 22nd, 2013 at 09:57 PM.
    -- Success achieved from tribulation --

IMN logo majestic logo threadwatch logo seochat tools logo