+ Reply to Thread
Results 1 to 2 of 2

Thread: How can I store structure in the file and read it back from file?

  1. #1

    How can I store structure in the file and read it back from file?

    I want to store below structure into the file.

    I also need to read it back.

    Code:
    //my structure layout is:
    struct MyData
    {
    	int Version ;
    	int Type ;
    	char Payload[100] ;
    } ;

    Please help.

  2. #2
    Try below code:

    Code:
    void StoreData()
    {
    	MyData myData ;
    	myData.Version = 1 ;
    	myData.Type = 1 ;
    	strcpy(myData.Payload, "My data") ;
    
    	FILE *pFile = fopen("C:\\mydata.txt", "w+") ;
    	if (NULL != pFile)
    	{
    		fwrite(&myData, sizeof(myData), sizeof(char), pFile) ;
    		fclose(pFile) ;
    	}
    
    	pFile = fopen("C:\\mydata.txt", "r+") ;
    	if (NULL != pFile)
    	{
    		MyData myData ;
    		fread(&myData, sizeof(myData), sizeof(char), pFile) ;
    		fclose(pFile) ;
    	}
    }
    It should help you.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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