Hmm. I read caduardo21's post differently.
Originally Posted by
caduardo21
Another question. This one is tricky for me...
If I try to open a file and it doesn't exist, my FILE pointer will be equal to NULL. Do I have to close the first stream before opening a new one? Here's the situation:
Code:
points = fopen("points.txt", "r");
if(points == NULL)
create_points_file();
/* should I fclose(points) here? */
points = fopen("points.txt", "r");
while(fgets(line, sizeof(line), points) != NULL)
printf("%s", line);
fclose(points);
Essentially, if it opened, close it.
Code:
#include <stdio.h>
int main(void)
{
static const char filename[] = "myfile.txt";
FILE *file = fopen(filename, "r");
if ( !file )
{
printf("creating %s\n", filename);
file = fopen(filename, "w");
if ( file )
{
int i;
for ( i = 0; i < 5; ++i )
{
fprintf(file, "data #%d\n", i + 1);
}
fclose(file);
}
}
file = fopen(filename, "r");
if ( file )
{
char line[80];
while ( fgets(line, sizeof line, file) )
{
fputs(line, stdout);
}
fclose(file);
}
else
{
puts("WTF???");
}
return 0;
}
/* my output
C:\Test>Test
creating myfile.txt
data #1
data #2
data #3
data #4
data #5
C:\Test>Test
data #1
data #2
data #3
data #4
data #5
*/
[edit]Standing corrected by the subsequent post.