Thread: Read a file

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    2

    Read a file

    Hello,

    I'm just curious as I'm new to programming. Whenever I want to read a file and get strings from the file. Say I have a file like this:

    ExampleFile.txt:
    Name: John Smith
    Age: 16
    Address: example, address, 12345
    ... and so on

    And the way i read the file and retrieve the information, I usually do it by reading the file line by line and tokenise each string. So I'll get an array of words. So my question is, is there a better way to do it?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    That is going to depend entirely upon what you're trying to achieve.

    The example you've given would be a poor candidate for tokenizing since you may well want the person's name and address as intact strings. In that case you could (for example) write a parser that see the word "Name:" and copies the right side of the string into a struct that holds the individual's information. "Age" could be converted to an integer and stored in the same struct... and so on.

    What you do with filed data and how you manipulate it is going to be dictated by the needs of the application you are working on.

  3. #3
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    If your program is the one creating the file, then you could look at using a random access file system, e.g. make a binary file and read/write to it with an array of structures. As Tater always says, there is no need for "human readable" files that are only going to be used by your program. Just search this forum and the internet for "random access files".

    Also, I'm sure Tater will be back along to post an example.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by AndrewHunter View Post
    Also, I'm sure Tater will be back along to post an example.
    Hey, it's your turn...

  5. #5
    Registered User
    Join Date
    Jul 2011
    Posts
    2
    Thanks for the quick replies.

    Most of the time, I did the way I mentioned above and I realised how inefficient it was towards the example problem above. I'll try the stuff you said.
    Last edited by Tzup89; 07-31-2011 at 10:38 AM.

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    The way you are presently doing it, breaking the lines into tokens, is the only way to do it. I think thats what C is all about, that you can analyze things down to the subatomic level. I dont think there is a way to token it while reading it, so you got to do all that stuff once you have read the file. Its tedious and hard but at least it can be done. Some languages cant even do that.

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by Linux Trojan View Post
    The way you are presently doing it, breaking the lines into tokens, is the only way to do it. I think thats what C is all about, that you can analyze things down to the subatomic level. I dont think there is a way to token it while reading it, so you got to do all that stuff once you have read the file. Its tedious and hard but at least it can be done. Some languages cant even do that.
    That is incorrect. There are many ways this problem can be solved as has been stated above. Just because you don't think something doesn't mean it isn't true. Please try to do some more research before making such a comment.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    Perhaps, it didnt come out right. I was trying to say, "the easiest way" is how he is doing it, without having to create binaries and arrays of structures, etc. I was just trying to start some interesting discussion on the virtues of C and its ability to parse coz it is very powerful. Maybe I didnt say it right but I wasnt trying to mislead anyone.

  9. #9
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    And again you are wrong. The easiest way to do this is with random access files. Don't hijack a thread because you want to have a discussion. I suggest you review structures and working with files if you think these topics are complex.

    If you want to discuss a technique start a new thread and refer the the threads in question.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Linux Trojan View Post
    The way you are presently doing it, breaking the lines into tokens, is the only way to do it. I think thats what C is all about, that you can analyze things down to the subatomic level. I dont think there is a way to token it while reading it, so you got to do all that stuff once you have read the file. Its tedious and hard but at least it can be done. Some languages cant even do that.
    Oh Bullsmut!

    Ok... he has an address line "123 AnyStreet, Anytown, Canada, A1A 1A1" ... how does toeknizing that string into words to anything except destroy the meaning of the data? He wants that as one contiguous string, not a list of words.

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Linux Trojan View Post
    Perhaps, it didnt come out right. I was trying to say, "the easiest way" is how he is doing it, without having to create binaries and arrays of structures, etc. I was just trying to start some interesting discussion on the virtues of C and its ability to parse coz it is very powerful. Maybe I didnt say it right but I wasnt trying to mislead anyone.

    How much simpler do you want it?

    Code:
    //random access file demo
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    #include <ctype.h>
    #include <string.h>
    
    #define FNAME "random.dat"
    
    // test data struct
    struct t_Record
      { int randnum;
        char word[16]; }
      Record;
    
    
    
    ///////////////////////////////////////////////////////
    // Random Access File Handlers
    //
    
    // open or create the file
    FILE *FileOpen(char* Filename)
      { FILE* pFile;
        pFile = fopen(Filename,"rb+");
        if (!pFile)
          pFile = fopen(Filename,"wb+");
        return pFile; }
    
    
    // Write a record to the file
    int WriteRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fwrite(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    // read a record from the file
    int ReadRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fread(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    
    ////////////////////////////////////////////////////////
    // this is for demonstration purposes only
    // you would not do this in a real program
    void InitFile(FILE* File)
     { int x, y;
       memset(&Record,sizeof(Record),0);
       for (x = 0; x < 1000; x++)
          { Record.randnum = rand();
            for (y = 0; y < ((Record.randnum % 15) + 1); y++)
              Record.word[y] = (rand() % 26) + 'a';
            Record.word[y] = 0;
            if (! WriteRecord(File,x))
              printf("Oh drat!");  } }
     
    
     
    //////////////////////////////////////////////////////////
    // program mains
    //
    int main (void)
      { FILE *File;
        int Quit = 0;
        int Rec = 0; // record number
    
        srand(time(NULL));
    
        File = FileOpen(FNAME); 
        if (!File)
          { printf("Curses foiled again!\n\n");
            exit(-1); }
    
        // write out 1000 test records  
        printf("Create a new file? (y/n)  ");
        if ( toupper( getchar() ) == 'Y')
          InitFile(File);
      
        // lets peek
        do
          { printf("Enter a record number (0 - 999) to load : ");
            if (! scanf("%d",&Rec) )
              Quit = 1;  // enter any letter to quit
            else 
              { // read and display the record 
               if (! ReadRecord(File,Rec) ) 
                  printf("Could not read record %d\n",Rec);
                else
                  { printf("-----\n");
                    printf("Record Number : %d\n",Rec);
                    printf("Number Value  : %d\n",Record.randnum);
                    printf("Record Name   : %s\n",Record.word);
                    printf("-----\n"); 
                    getchar();
                    printf("Do you want to rename this record (y/n)? ");
                    if ( toupper( getchar() ) == 'Y')
                      { printf("Enter a new name : ");
                        if ( scanf("%s",Record.word) )
                          WriteRecord(File,Rec);  } } }
          } while (! Quit); 
    
    
        fclose(File);
        return 0; }

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Linux Trojan View Post
    Perhaps, it didnt come out right. I was trying to say, "the easiest way" is how he is doing it, without having to create binaries and arrays of structures, etc. I was just trying to start some interesting discussion on the virtues of C and its ability to parse coz it is very powerful. Maybe I didnt say it right but I wasnt trying to mislead anyone.
    Actually, the whole point of THIS thread is to answer the OP's question.

    If you want to start an interesting discussion on parsing files... start your own thread, don't hijack someone else's.

  13. #13
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    Tater: Thats alot of code to analyze, and I will in time. But for now, I just thought that for a newbie, it would be easier to break the info into tokens and then just use STRCAT to sew it all back up again. I stand corrected. I gotta run!

  14. #14
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by CommonTater View Post
    ...
    If you want to start an interesting discussion on parsing files... start your own thread, don't hijack someone else's.
    Quote Originally Posted by AndrewHunter View Post
    ...Don't hijack a thread because you want to have a discussion.
    ....If you want to discuss a technique start a new thread and refer the the threads in question.
    Hmm...it appears we are in agreement again. Watch out Tater, your rep around here is going to take a serious nose dive.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    Oh Bullsmut!
    I like animals as much as the next guy, but apparently not as much as you!


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Open a file, read it ... and ... read it again
    By Tiago in forum C Programming
    Replies: 1
    Last Post: 04-17-2010, 03:32 AM
  2. File Handling -Read write and edit a file
    By aprop in forum C Programming
    Replies: 3
    Last Post: 02-27-2010, 02:01 PM
  3. How can I know the actual bytes read in a file read
    By pliang in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2005, 04:23 PM