#include<stdio.h>
main()
{
FILE *fp;
fp=fopen(*PR1.c","r");
if(fp==NULL)
{
puts("cannot open");
exit()
}
}
--------------
in this program why they are using *fp and pl reason full program..
and also how fp=fopen(*PR1.c","r"); works
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen(*PR1.c","r");
if(fp==NULL)
{
puts("cannot open");
exit()
}
}
--------------
in this program why they are using *fp and pl reason full program..
and also how fp=fopen(*PR1.c","r"); works
The pointer is an address to something in your memory (RAM).
fopen will create an "object" to handle the requested file, in the memory. But for you to be able to use this object, to manipulate the file, you have the address returned which you store in a pointer :)
Also, you probably heard about the so-called memory leaks.
That's what occur if "objects" aren't deleted from the memory (RAM) after they have been used. You have to do it, in this case, with fclose(fp);.
Imagine what would happen if your program iterated through thousands of files, and never fclosed :O Your computer risks running out of memory, and then you crash.
You can read the manual for fopen to see how it works.
Googling "fopen C" works: http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
I'd say you have a syntax error anyway, don't you want to write
fopen("PR1.c", "r");
Good luck, and welcome to DaniWeb.
And just a side note:
On DaniWeb, please post your code in the CODE tags.
This highlight syntaxes and retains tabulations. That makes it easier for us to read and comment on your code.
It's not a big deal with such a small code you had, but please get used to it anyway.
> why they are using *fp
Edward assumes you mean why is it
FILE *fp = fopen(...)
instead of
FILE fp = fopen(...)
Under the hood, it looks kind of like the following.
struct FILE {
HANDLE h; /* System file handle */
BUFFER b; /* I/O buffer */
FLAG f; /* State flags */
};
FILE _files[FOPEN_MAX];
int _curr_file = 0;
FILE *fopen(...)
{
FILE *fp = NULL;
if (_curr_file < FOPEN_MAX) {
fp = &_files[_curr_file++];
fp.h = /* Get a system file handle */
fp.b = GetIoBuffer();
fp.f = IO_STATE_GOOD;
}
return fp;
}
But why does fopen return a pointer? The biggest reason in Ed's opinion is that a FILE object's members need to be changed and persist across function calls. Building pass by reference directly into the type instead of leaving the onus on programmers to get it right makes everything easier. :)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.