Thread: Using Text Files and Functions

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

    Using Text Files and Functions

    Here is my situation:
    I have a text file with one line that contains:
    1;2;3;4;5;6;7;8;9;10

    Now I have a function that deals with each number separately. So I have myFunctionOne that deals with the number 1, I have myFunctionTwo that deals with the number 2, etc. I send in my text file to each function, and the function pulls out the specific number.

    Am I allowed to call my functions as follows:

    FILE *file

    file = fopen("MyTextFile.txt","r");
    myFunctionOne(file);
    myFunctionTwo(file);
    myFunctionThree(file);
    fclose(file);

    Can I just open the file, send it to all my functions, then close the file, or do I have to close the file and reopen it after every function call?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You don't have to close the file, but you probably need to rewind it, depending on how your functions are set up. (Rewinding sets the file pointer back to the beginning of the file.)

    I have no idea what you're doing here; however, if you only have one line of text, why not write one function that reads them all in, into an array or a struct or something, and then you can refer to that array or struct or something, rather than always going back to the text file?

  3. #3
    Registered User
    Join Date
    Jul 2008
    Posts
    133
    Funny situation. But if your functions are reading file byte by byte, and stop on ';' byte, then rewind (fseek()) won't be necessary. But you have to be careful if one or more numbers are missing in file, or some "alien" characters appear...

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Wouldn't it be simpler to do something like this:

    Code:
    while (you have not reached the eof of the file)
       read the next number
       switch(number)  {
           case 1: your #1 logic, here; or call your function 1; break;
           case 2;   "     #2   same for #2; break;
    
       }//end of switch 
       read the semi-colon, if you haven't reached the end of the file, yet.
    }//end of while

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help creating multiple text files
    By Tom Bombadil in forum C Programming
    Replies: 19
    Last Post: 03-28-2009, 11:21 AM
  2. Replies: 7
    Last Post: 02-01-2009, 04:53 PM
  3. Passing functions between files
    By Duskan in forum C Programming
    Replies: 9
    Last Post: 04-17-2007, 07:44 AM
  4. header and source files
    By gtriarhos in forum C Programming
    Replies: 3
    Last Post: 10-02-2005, 03:16 AM
  5. displaying text files, wierd thing :(
    By Gades in forum C Programming
    Replies: 2
    Last Post: 11-20-2001, 05:18 PM