Just wondered if anyone could provide some hints on file I/O? It needs to save structures to a file if that helps
Printable View
Just wondered if anyone could provide some hints on file I/O? It needs to save structures to a file if that helps
This is just a snippet of code.
/*srcfile is the file pointer*/
/*src_file is a filename passed by the user*/
if ( (srcfile = fopen (src_file, "r") ) == (FILE *) NULL )
{
printf ("cannot open %s \n", src_file);
exit (1); /*fopen returns NULL if problems so exit program*/
}
printf ("\n");
for (j=0; j<40; j++) {
/*reading in file into sturcture*/
result = fscanf (srcfile, " %d", &rcd_shared->rcd_data [j].ch);
if (result == EOF) break; /*break out when end of file */
fscanf (srcfile, " %d", &rcd_data [j].rt);
fscanf (srcfile, " %c", &rcd_data [j].tr);
fscanf (srcfile, " %d", &rcd_data [j].sa);
fscanf (srcfile, " %d", &rcd_data [j].wd);
rcd_shared->rcd_Ctrl.number_of_signals = j + 1;
}
fclose (srcfile); /*must close file*/
not the cleanest example but it gets the job done.
Made code of unregistered a bit more nice.
Avoid using the break-statement in a for-loop. Also avoid the use of the exit()-function. When needing these, it means that your program is bad-structured.Code:/* the return value is TRUE if everything went OK, else FALSE */
bool return_value;
/* pointer to the file */
FILE *srcfile;
/* name of the file */
char *srcfile_name;
/* try to open the file for read only */
srcfile = fopen (srcfile_name, "r");
if (srcfile != NULL)
{
/* file is opened */
for (j = 0; (j < 40) && (result != EOF); j++)
{
/* reading in file into structure */
result = fscanf (srcfile, " %d", &rcd_shared->rcd_data [j].ch);
result &= fscanf (srcfile, " %d", &rcd_data [j].rt);
result &=fscanf (srcfile, " %c", &rcd_data [j].tr);
result &=fscanf (srcfile, " %d", &rcd_data [j].sa);
result &=fscanf (srcfile, " %d", &rcd_data [j].wd);
rcd_shared->rcd_Ctrl.number_of_signals = j + 1;
}
/* close file */
fclose (srcfile);
return_value = TRUE;
}
else
{
printf ("Cannout open %s\n", srcfile_name);
return_value = FALSE;
}