I suggest that you try:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
/* Write "hello world!" to "bacon.txt" */
char text[100];
char file_name[100] = "bacon.txt";
FILE *fp = fopen(file_name, "w");
if (!fp)
{
fprintf(stderr, "Could not open file for writing.");
return 0;
}
fprintf(fp, "%s\n", "hello world!");
fclose(fp);
/* Read from "bacon.txt" */
fp = fopen(file_name, "r");
if (!fp)
{
fprintf(stderr, "Could not open file for reading.");
return 0;
}
if (fgets(text, sizeof(text), fp))
{
text[strcspn(text, "\r\n")] = '\0'; /* remove newline if it exists */
printf("%s content: %s\n", file_name, text);
}
else
{
fprintf(stderr, "Read error.");
}
fclose(fp);
return 0;
}