Reputation: 17
I am just learning how to work with file IO and I am probably super wrong. I need to create and write to a file a list of city names and its population density.I am able to print the list properly formatted in standard output using a for-loop, but am unable to write it to the file. Like I said when using a printf statement, it works just fine, but the (fopen, "w") fprintf isnt working. Where am I going wrong?
printf("Create new file name:\n");
scanf("%s", outfile);
fp = fopen(outfile, "w");
for(i=0;i<10;i++){
fprintf("%s %.2f\n", veg[i].name, density );
}
fclose(fp);
I expect the file to be populated with the list of cities, but I the program is crashing instead. I receive this error message.
"Incompatible pointer types passing 'char [10]' to parameter of type 'FILE *' (aka 'struct __sFILE *')"
Upvotes: 0
Views: 108
Reputation: 43
You need to specify the file to write in in your fprintf() call.
fprintf(outfile,"%s %.2f\n", veg[i].name, density );
Here's the doc : https://en.cppreference.com/w/c/io/fprintf
You also need to return whether or not your fopen failed.
if (fp != NULL)
{
printf("File created successfully!\n");
}
else {
printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
Be aware that if you use Visual studio, you'd have to use fprintf_s()
instead where you'd have to specify the sizeof your string.
Upvotes: 1