Hi All,
I have a simple code that writes and reads from file :
Code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
FILE *fptr;
char ch[]="He is a good boy";
char *str;
//char str[40];
fptr = fopen("anoop.txt","w+");
if(fptr!=NULL)
{
fputs(ch,fptr);
fflush(fptr);
///fclose(fptr);
}
fgets(str,40,fptr);
printf("Contents:%s",str);
fclose(fptr);
getch();
return 0;
}
Questions;
1. Why doesn't it ouput the above string? what is wrong with the piece of code?
Following piece of code outputs the string correctly:
Code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
FILE *fptr;
char ch[]="anoop is a good boy";
char *str; ///======================= QLine 1
//char str[40];
fptr = fopen("anoop.txt","w+");
if(fptr!=NULL)
{
fputs(ch,fptr);
fflush(fptr); ///======================= QLine 2
fclose(fptr);
}
fptr = fopen("anoop.txt","r");
if(fptr!=NULL)
{
fgets(str,40,fptr);
//puts(str);
printf("Contents:%s",str);
fclose(fptr);
}
getch();
return 0;
}
Questions:
1. How come it works? shouldn't it crash with the Qline1 ?
w.r.t Qline1: *str is not initialized shouldn't crash as it may be pointing some where?
2. Is the line Qline2 required?
Thanks in advance