Jump to content

How to save a structure to a file? C

- - - - -

  • Please log in to reply
12 replies to this topic

#1
alex1

alex1

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
Hello guys!I have this structure:

struct Customers {

       char Fname[20];

       char Lname[20];

       int customerId;

       int paperId;

       int room;

       int age;

       float roomPrice;

};


I have this case in my menu:

case 1:{ 

            system("cls");

            printf("Give Customer's Last Name: ");

            scanf("%s",&c.Fname);

            printf("Give Customer's First Name: ");

            scanf("%s",&c.Lname);

            printf("Give Customer's age: ");

            scanf("%d",&c.age);

            printf("Give Customer's ID: ");

            scanf("%d",&c.customerId);

            printf("Give Customer's Card ID: ");

            scanf("%d",&c.paperId);

            printf("Give Customer's room: ");

            scanf("%d",&c.room);

            printf("Give Customer's room price: ");

            scanf("%f",&c.roomPrice);

            system("pause");

            break;

            }


I'm new at the files world...How can I save the structure to a file? I searched really hard for this,but I found no solutions at all.
Can someone help me?

Any help is highly appreciated!

Thanks in advance!

#2
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
File input and output is part of stdio.h. You'd need to use the fopen function to open your file, then fwrite to write your structure to it, passing a pointer to your structure just as you would do with any other data type. When you are done writing to your file, you'll want to close it with fclose. Hope this helps :D
Latinamne loqueris?

#3
alex1

alex1

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
I have never ever used files,so I have no idea of the general syntax.. :(

#4
HemStar

HemStar

    Newbie

  • Members
  • Pip
  • 3 posts
FILE *fopen(),*fp, *fp1, *fp2, *fp3;
The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.

The file <stdio.h> contains declarations for the Standard I/O library and should always be included at the very beginning of C programs using files
Constants such as FILE, EOF and NULL are defined in <stdio.h>.

fp= fopen( “prog.c”, “r”) ;

The above statement opens a file called prog.c for reading and associates the file pointer fp with the file.

The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar©.

Thus the statement

c = getc(fp);

reads the next character from the file referenced by fp and the statement

putc(c,fp);

writes the character c into file referenced by fp.



/* file.c: Display contents of a file on screen */


#include <stdio.h>

void main()
{
FILE *fopen(), *fp;
int c ;

fp = fopen( “prog.c”, “r” );
c = getc( fp ) ;
while ( c != EOF )
{
putchar( c );
c = getc ( fp );
}

fclose( fp );
}

HERE YOU JUST NEED TO CHANGE the Character 'c' to a STRUCTURE VARIABLE
NOTE THIS PROGRAM IS FOR READING A FIE"S DATA INTO A STRUCTURE......THE REVERSE CAN BE DONE IN THE SAME WAY

#5
alex1

alex1

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
THANK YOU!!!!

#6
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US
I don't know whether this is confusing or not, but Win32 API file pointers are different from C file pointers. In C, it's called a file pointer, while in Win32 it's called a file handle. The term file pointer, in Win32, usually means the current read/write position of the file handle in the file.

For example, when you first open the file, you are given a file handle. The handle's file pointer is 0, because you're at the beginning of the file. When you read, for example, 100 bytes from the file, the file pointer is:
  • 100, if the file size is not less than that.
  • the size of the file, if the file is less than 100 bytes in size.

If the file pointer is 100 right now, and you write 16 bytes to the file, 16 bytes are written to the address space starting at 100 and stopping at 116, which is what the file pointer gets set to next. You can also change the file pointer, in order to jump to a different position inside the file, for reading or writing, by setting the file pointer. This is done with the SetFilePointer () Win32 API function. fseek () is the C version of "setting the file pointer."

In Win32, MS-DOS, and even Linux, a file handle is used for accessing files. I don't know about other operating systems, but in Win32 a file pointer is a read/write position or "cursor" address relative to the start of the file. In C, what you're working with, file pointers is the term used to describe file handles, and I don't know what the word for Win32 file pointers would be in C.

#7
phuocdai11

phuocdai11

    Newbie

  • Members
  • PipPip
  • 12 posts
oh! you i can do it with

void writestruct(customer swrite)

{

FILE *f=fopen("data","w");

fwrite(&swirte,1,sizeof(swrite),f);

fclose(f);

}

it's very simple!:rolleyes:

#8
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US

phuocdai11 said:

oh! you i can do it with

void writestruct(customer swrite)

{

FILE *f=fopen("data","w");

fwrite(&swirte,1,sizeof(swrite),f);

fclose(f);

}

it's very simple!:rolleyes:

I don't believe you can do it like that; it'll only write like 4 bytes and it'll only write the pointer to the structure, not the data from it. Also, you need to use binary mode, because structures are rarely ever, if not never, text-only. You'll also need the size to be manually provided, because there's not really a way to tell what size the structure is. Perhaps something like this:
struct some_struct { 

int id; 

int something; 

}; 


void WriteStruct (){ 

struct some_struct ss;    // This might be wrong; I'm not sure. 

void * pStruct= &ss; 

int sStruct= sizeof (some_struct); 

FILE * hFile= fopen ("the_file.txt", "wb");   // The 'b' makes use of binary mode. 

fwrite (sStruct, 1, pStruct, hFile); 

fclose (hFile); 

} 

If you get some compiler wrong type mismatch errors, just use type casting to pacify the compiler :D ; I'm just not sure if I got all the types right for the fopen () and fwrite () functions :) .


By the way, you're not supposed to just give away code; I think it won't matter that much right now because the OP probably already has something written, but still, for the future, helping is not the same as doing someone else's homework (or just work).

#9
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
Other than the fact that he opened the file in text mode, phuocdai11's solution was fine. You are supposed to pass the data to be written by reference. I also don't see what makes you say there is no easy way to tell what size the structure is, you'd just have to use sizeof(struct [whatever]) if you weren't using a typedef for the struct (unless you are in C++ of course).
Latinamne loqueris?

#10
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US
There's no way to tell the size if the variable is not local - that is, if we just have a pointer to the structure and that's it, which seems like the case to me.

#11
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
Here is the code I was testing it with:

#include <stdio.h>


typedef struct Testing_t

{

	int item1;

	int item2;

}Testing;


int WriteStruct(FILE *file, Testing input)

{

	fwrite(&input, 1, sizeof(input), file);

}


int ReadStruct(FILE *file, Testing *input)

{

	fread(input, 1, sizeof(*input), file);

}


int main(int argc, char **argv)

{

	Testing s1;

	Testing s2;

	FILE *testingfile;


	s1.item1 = 1;

	s1.item2 = 2;


	testingfile = fopen("Testingfile", "wb");

	WriteStruct(testingfile, s1);

	fclose(testingfile);


	testingfile = fopen("Testingfile", "rb");

	ReadStruct(testingfile, &s2);

	fclose(testingfile);


	printf("%d\n%d\n", s2.item1, s2.item2);


	return 0;

}


It outputs 1, a newline, and then a 2. I suppose that means it should work? Unless I did the coding wrong?

EDIT: In the case of the inputted struct to the function for writing being passed as a void pointer, then yes, you would need to pass the size as well as then the compiler would have no way of inferring the size. However, I didn't see this as the case since in the function example he gave he specified the type.
Latinamne loqueris?

#12
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Writing binary structures to file will cause issues if another system of different byte order reads it. Often people prescribe their own format, or use text if possible so that at least order is known and error checking can be easier done.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users