Advertisement

reading in files question

Started by May 14, 2001 02:07 PM
0 comments, last by omegasyphon 23 years, 9 months ago
how would i go about reading in a file into an array or list?
you could try:


int main()
{
FILE *fp;

char buffer[10];

// assume Object is a struct
Object list[20];


fp=fopen("file.txt","r");

if (!fp)
{
// file not found
exit(1);
}

// read in 10 characters
fread (buffer,sizeof(buffer),10,fp);
// for structures
free (list,sizeof(Object),20,fp);

fclose (fp);

return 0;
}


the fread() function prototype is (I think, but check your compiler manual)

int fread (void *buffer, int size, int amount, FILE *file_pointer);

* the buffer is what you want to load in

I am not sure if you may need to send it like this

fread (&buffer,sizeof(buffer),10,fp);

with arrays I don''t think you need the & but I am not sure.

* the size is simply the sizeof() a type such as your struct, or char, int float or whatever.

* amount is the amount you want to load in

e.g. to load an array of chars you could so this

for (int i=0; i<10; i++)
fread (&buffer,sizeof(char),1,fp);

but easier is

fread (buffer,sizeof(buffer),10,fp);

the second loads all ten chars directly into buffer, but the first needs a loop which loads 1 (notice the amount) char at a time into buffer. that first method is not really necessary and not worth the extra typing of the loop, but still works (I use to use this method until I discovered the second approach)<br><br>* file_pointer is simply the file pointer but everyone knows that.<br><br><br>PLEASE EXCUSE ME AND CORRECT ME, ANYONE IF I AM WRONG, I AM WRITING THIS OFF THE TOP OF MY HEAD AND I USUALLY REFER TO MY COMPILIER''S DOCUMENTATION WHEN USING FILE I/O FUNCTIONS.<br><br>Hope I helped in anyway<br><br>Dark Star </i>
---------------------------------------------You Only Live Once - Don't be afriad to take chances.

This topic is closed to new replies.

Advertisement