Results 1 to 2 of 2

Thread: Need help with reading/writing dat file with struct !

  1. #1
    New Member Etsho's Avatar
    Join Date
    Apr 11
    Posts
    10

    Question Need help with reading/writing dat file with struct !

    Hello Guys ,

    Iam new in c++ coding , so i want you to help to find a solution for this.

    I need to read and write to the dat file using this struct:

    Code:
    typedef struct contact
    { 	
     char first[100]; 	
     char last[100]; 	
     char phone[50]; 
    }contact;
    Thanks

  2. #2
    New Member
    Join Date
    Jul 12
    Posts
    5

    Re: Need help with reading/writing dat file with struct !

    For opening the .dat file you can use this code to display the text in the file to your cmd:
    i'll try to explain step by step what down here since you're new to c++ coding.
    Code:
    // reading a text file
    #include <iostream> 
    #include <fstream> //class for both write and reading files
    #include <string> //don't forget to include this stream! else you can't read strings
    using namespace std;
    
    int main () { 
      string line; //define line as new string
      ifstream myfile ("FILE.dat"); //opens the file for reading
      if (myfile.is_open()) //if the file is open 
      {
        while ( myfile.good() ) //new loop while myfile.good()
        {
          getline (myfile,line); //so as long as myfile.good() is true then getline from you're file
          cout << line << endl; //print's the line out on your screen
         //when you hit the bottom of your file then myfile.good() is no longer true so
        }
        myfile.close(); //close the file 
      }
    
      else cout << "Unable to open file";  // if you could not open the file then display an error
    
      return 0; //return 0 means there were no errors.
    }
    and for writing to the file you'd prob need something like this:

    Code:
    // writing on a text file
    #include <iostream>
    #include <fstream> 
    using namespace std;
    char first[100]; 	
    char last[100]; 	
    char phone[50]; 
    int main () {
      ofstream myfile ("FILE.dat"); //open file for writing 
      if (myfile.is_open()) //if you're file is open then
      {
        //writes your 3 chars to the file. you can use myfile the same as cout to write something to your file
        myfile << first << endl;
        myfile << last << endl;
        myfile << phone << endl;
        myfile.close(); //when you're done close the file
      }
      else cout << "Unable to open file"; //if there was an error display this
      return 0; //return 0 if there was no error 
    }
    I hope this helps you. More info about reading and writing files can be found here: Writing & reading files
    Last edited by TechDude; Jul 23rd, 2012 at 09:59 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •