here's the code i wrote:
#include <stdio.h>
#include <stdlib.h>
void Print_File(FILE *f)
{
fopen("f", "r");
char s = fgetc(f);
while (s != EOF)
{
printf("%c", s);
s = fgetc(f);
}
fclose(f);
}
int main(void)
{
FILE *ptr = fopen("info.txt", "a");
if(ptr == NULL)
{
printf("Invalid Input\n");
return 1;
}
char *c = malloc(sizeof(char) * 101);
printf("One entry cannot be more than 100 characters long!\n");
printf("Enter your text here - ");
scanf("%[^\n]%*c", c);
fprintf(ptr, "%s\n", c);
fclose(ptr);
Print_File(ptr);
free(c);
}
After Executing the program on command line, when i manually open the file, it is updated alright! But the file is not printed! Did I write the Print_File() function wrong?
Look at the manual page for fopen()
. It takes a file name as first argument, and it returns a FILE *
. What you are doing is wrong.
You should change this:
fopen("f", "r");
To this:
FILE *f;
f = fopen("file-name-here", "r");
if (f == NULL) {
puts("Error opening file!");
exit(1);
}
Secondly, passing ptr
, which is a closed file, to the function, is useless. Either open it before calling the function (and at that point do not use fopen()
inside it) or just declare the function as taking no arguments and open it inside.
Option 1:
void Print_File(FILE *f)
{
// ... use already opened file ...
}
// Then in main:
ptr = fopen("file-name-here", "r");
if (ptr == NULL) {
puts("Error opening file!");
exit(1);
}
Print_File(ptr);
Option 2:
void Print_File(void) // void == takes no arguments
{
FILE *f;
f = fopen("file-name-here", "r");
// ...
}
// Then in main:
Print_File();
Lastly, fgetc()
returns an int
. You need to use an int
variable to hold the result, or you won't be able to distinguish between a valid character and EOF
:
int s = fgetc(f);
while (s != EOF)
{
// ...
Complete working example:
#include <stdio.h>
#include <stdlib.h>
void Print_File(FILE *f)
{
int s = fgetc(f);
while (s != EOF)
{
printf("%c", s);
s = fgetc(f);
}
fclose(f);
}
int main(void)
{
FILE *ptr = fopen("info.txt", "a");
if(ptr == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
char *c = malloc(sizeof(char) * 101);
if (c == NULL) {
printf("Error allocating memory.\n");
return 1;
}
printf("One entry cannot be more than 100 characters long!\n");
printf("Enter your text here - ");
scanf("%[^\n]%*c", c);
fprintf(ptr, "%s\n", c);
fclose(ptr);
ptr = fopen("info.txt", "r");
if(ptr == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
Print_File(ptr);
free(c);
return 0;
}
Output:
$ gcc prog.c -o prog
$ ./prog
One entry cannot be more than 100 characters long!
Enter your text here - HELLO WORLD
HELLO WORLD
$ ./prog
One entry cannot be more than 100 characters long!
Enter your text here - HELLO WORLD AGAIN
HELLO WORLD
HELLO WORLD AGAIN