Open file to read and write and or append to it. If not there then create it, then reopen it without closing it first. is that safe seeing how nothing yet really has been done to it.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char **argv)
{
if (argc < 2)
{
printf("no file given to open ( %s )\n", argv[argc]);
exit(1);
}
char str1[10], str2[10], str3[10];
int year;
int count = -1;
FILE *fp;
// open user given file off cli
fp = fopen(argv[1], "a+");
if (fp == NULL)
{ // if file not there then just create it.
fprintf(stderr, "File not found\n");
fp = fopen(argv[1], "w");
} // if succesful create let user know
if (fp != NULL)
printf("file created\n");
else
{
printf("No file\n"
"could not create it either\n");
exit(1);
}
// now reopen for reading and appending to file <- is that the safe/ok way?
fp = fopen(argv[1], "a+");
fputs("We are in 2012", fp);
rewind(fp);
count = fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 |%s|\n", str1 );
printf("Read String2 |%s|\n", str2 );
printf("Read String3 |%s|\n", str3 );
printf("Read Integer |%d|\n", year );
printf("COUNT IS %d\n", count);
fclose(fp);
return 0;
}
it worked with out any file, it created one then added to it then printed out the results with no errors