More C Programming help!

Joined
5 Aug 2006
Posts
11,419
Location
Derbyshire
I am learning to write to files in c programming. I have a program that reads a file and can display that file on the screen (it is a little tricky as the file has table-style data in it, so there is an array of structures, with a structure holding a line of data).

If I have this (this is not what I have, but something similar as I want to try myself).
Code:
struct people
{
int age;
double weight, height;
};
struct people people_array[100];
How would I write this to a .dat file??
I think I need a for loop with a counter to increment a counter, so it writes a line, increments, writes next line, increments etc etc until the end of file is found.

This is just a tutorial but I have spent hours trying to find the right approach. It is really bugging me!

Many thanks:)
 
Last edited:
My lecture notes have plenty of example of writing stuff to .dat files, but nothing on an array of structures!

A 'for' loop is needed I am quite confident on that:)

Whats the FPTR?
iirc I need FILE *output_stream somewhere and an fprintf or sprint f to write to a string?

I see you called the file tmp (any name will do I think), why you written "rw"? r is to read, w to write but can both be done at the same time?

My C skills are not much better than novice I am afraid!
 
Last edited:
you need to do something along the lines of:

Code:
FILE* fp;
fp = fopen("file.bat","rw");
for(i=0;i<100;i++) {
    fprintf(fp, ..........);
}
fclose(fp);

Haven't checked this though ^^^^

Changed the rw bit to r and it works:p (No idea what rw means btw!)

Is fclose(fp) absolutely essential?? The compiler shows no errors if it isn't there.
 
Back
Top Bottom