raam said:
hi all,
thanks for the reply.
This is the code
#include <stdio.h>
#include <conio.h>
Be aware that this header is specific to the Microsoft platform, and is
not available everywhere.
#include <stdlib.h>
main(){
This line should be written as
int main(void) {
First of all, implicit typing (assuming a function returns int unless
otherwise specified) is a reliable source of errors, and second of all,
it's no longer supported in the latest version of the C standard.
FILE *p;
struct mm{
int a[100];
};
struct mm *n;
int i;
n = (struct mm *)malloc(sizeof(struct mm));
Unless you are working with a *very* old implementation (pre-C89),
don't cast the result of malloc().
First of all, malloc() returns a void*, which can be implicitly
converted to any other object pointer type. Second of all, if you
forget to #include <stdlib.h> or otherwise not have a prototype for
malloc() in scope, casting the result will prevent the compiler from
issuing a diagnostic, and you may experience some weird problems at
runtime.
Rewrite that line as
n = malloc(sizeof *n);
"sizeof *n" is synonymous with "sizeof(struct mm)", which is a little
easier to read, and if you ever change the type of n, you don't have to
make the corresponding change to the malloc() call.
*ALWAYS* check the result of malloc() before trying to use it.
printf( "\n Press any key ");
getch();
Again, be aware that any functions from the conio library are specific
to the Microsoft platform, and will not be universally available.
for(i = 0 ; i<100 ; i++)
n->a= i;
p = fopen("example.txt","w");
Since you're using fread() and fwrite(), you'll want to open the file
in binary mode, like so:
p = fopen("example.txt", "wb");
BTW, it's *always* a good idea to check that the return value of
fopen() isn't NULL, just in case the file could not be created.
for(i = 65;i<75;i++)
printf("%d, ",n->a);
In order to guarantee that the text shows up on the screen, either
print a newline or call fflush(stdout) at this point.
getch();
fwrite(n,sizeof(struct mm),1,p);
Again, you can replace sizeof(struct mm) with sizeof *n.
fclose(p);
for(i = 0 ; i<100 ; i++)
n->a= 0;
p = fopen("example.txt","r");
Same thing as above; replace "r" with "rb", and make sure to check the
result isn't NULL before continuing.
fread(n,sizeof(struct mm),1,p);
fclose(p);
p = fopen("example1.txt","w");
fwrite(n,sizeof(struct mm),1,p);
fclose(p);
for(i = 65;i<75;i++)
printf("%d, ",n->a);
printf( "\n Press any key ");
getch();
free(n);
exit(0);
}