Thread: Advice reading lines from a text file.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    10

    Advice reading lines from a text file.

    I am tring to figure out the best way to go about doing this.

    Say the user clicks the mouse button or hits a key on the keyboard. It would open a text file, and read a line into the program. Then Separate the number from the message. Then the user clicks the button again. It reads the next line in.

    Not sure how visual novels do it, but that is what I am trying to do here. The number would represent where in the story you are. It would keep track. Then come the message after the number.

    I though about formatting a text file like:
    0 Hello World.
    1 This is a example tutorial done in c.
    2 etc...
    ...
    10 Some text here.

    My first question is would I use something like Fgets() to read the whole file in. Seprate the numbers from the message, store the number into a variable, and store the message into a variable.

    Maby someone on here can show me how to read a line in. Then seprate the number from the string. I understand how to use fgets somewhat. I can do this with it.

    Code:
    #include <stdio.h>
    
    int main() {
      char c[50];
      FILE *file; 
    
      file = fopen("story.txt", "r"); 
    
      if(file==NULL) {
        printf("Can't open story file.\n");
        return 1;
      }
      else {
        printf("Story File Open.\n\n");
        
        while(fgets(c, 50, file)!=NULL) { 
          printf("String: %s", c);        
        }
        fclose(file);
        return 0;
      }
    }
    Now the question remains. If I use the fgets method. I am guessing I write the split code for the number and string inside the while statement. Which C function do I use. I am not to good at strings in C yet. Which C function will take a line, and seprate the interger number from the string, and store them into two variable?

    One more question if I go the Fgets route. What if the story.txt starts to get big. 1000 lines of story lines. Would that take up to much space to store into memory? Maby I can seprate them into multiple story.txt files. Each with a certain numbers of lines.
    Last edited by Fujitaka; 08-11-2009 at 09:19 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading issue, mixed text file
    By hawaiian robots in forum C Programming
    Replies: 7
    Last Post: 05-22-2009, 04:38 AM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Reading lines from a file
    By blackswan in forum C Programming
    Replies: 9
    Last Post: 04-26-2005, 04:29 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM