Guys before i post my problem , lemme say that, i HAVE gone through the previous blogs/forums on daniweb, so please dont get annoyed with this topic again.
But none of them answer my question
My question is, "How do you write a structure to a file and retrieve data from it.
1)I think fwrite is the best option. Assuming s is the structure instance, you could use a code like
fwrite(&s,sizeof(s),1,fp);
But the problem is, this doesnt work if the structure contains int.
Why ?????
Because, all though the 'int' is saved in the file(in disk), a text doc wont be able to display because it only displays ascii characters.
2)So the way out would be to convery the number to a string , and then write into the file.So even the text doc will be able to display it char-by-char
3)This sound logically flawless. But after converting the number to a string, how do you make that string also a part of the structure so that i can still do my
fwrite(&s,sizeof(s),1,fp);
4)OK so i tried doing this. I am storing the number 0 as roll no. Notice the small tweak i did, 0 + '0'. So it displays even in the text doc cuz its actuallt printing ascii of (0+48). But clearly this doesnt work if the number is greater than 0.
#include<stdio.h>
#include<conio.h>
struct mystruct
{
int i;
char ch;
};
int main(void)
{
FILE *fp;
char* data;
struct mystruct s;
clrscr();
if((fp= fopen("e:\\tc1\\bin\\tceg.txt", "wb")) == NULL) /* open file TEST.$$$ */
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
s.i = 0+'0';
s.ch = 'A';
fwrite(&s, sizeof(s), 1, fp); /* write struct s to file */
fclose(fp); /* close file */
rewind(fp);
fp=fopen("e:\\tc1\\bin\\tceg.txt", "rb");
fgets(data,100,fp);
printf("\nThe data read from the file is : %s",data);
getch();
return 0;
}
5)Guys , so basically can you help me with a code that will take any integer (PART OF A STRUCTURE) and display it on the text doc.