PDA

View Full Version : fopen & fclose


BiosMarcel
24/02/2016, 08:28 AM
Hello,

I do have a question about some scenarios:


stock write(exmapletext[])
{
new File:file = fopen(path, io_append);
fwrite(file, exmapletext);
fclose(file);
return 1;
}


i open the file and close it at the end, is it even necessary to close it or will it be closed anyways when the variable isn't needed anymore?

So would that be exactly the same?


stock write(exmapletext[])
{
new File:file = fopen(path, io_append);
fwrite(file, exmapletext);
return 1;
}


and what happens if i just open it like that:


stock write(exmapletext[])
{
fopen(path, io_append);
return 1;
}


will the file still be opened but unaccessable after the function has been used?

K0P
24/02/2016, 08:48 AM
fopen
File can't be read if its open,you need to save the file id in a variable as done here:
new File:file = fopen(path, io_append);
And then make changes to the file using that variable ('File')

BiosMarcel
24/02/2016, 08:51 AM
Ofc i know that i cant access it if i dont put the handle into a variable ut that wasnt my question

K0P
24/02/2016, 08:55 AM
stock write(exmapletext[])
{
fopen(path, io_append);
return 1;
}
Opening a file like this will not be able to function as you are not saving it in a variable,my previous answer was its answer

If you want to do is without variable,than I think this will be the way to do it:
fwrite(fopen(path, io_append) , "Text here");

BiosMarcel
24/02/2016, 09:09 AM
The only thing i wanted to know is if there is some kind of garbage collection if the file handle (file) isn't in use anymore, i don't need u to tell me what i know already

Threshold
24/02/2016, 09:24 AM
No, the file stays open. I'm not 100% sure on the side effects of not closing the file, but you should always close the file if you don't plan on using it. (I'm talking about immediate use, not a "Oh, I will use it later, so I'll keep it open")

You also have ftemp, which can be used to create files that are deleted upon closing them.

Either way, you should always close the file after you're done with it, instead of leaving it open for later use.

BiosMarcel
24/02/2016, 11:47 AM
Well, in my case i did that


flength(fopen("FILENAME.TXT"))


i now replaced that with


stock getFileSize(filename[])
{
new File:sizetoget = fopen(filename,io_read);
new fileLength = flength(sizetoget);
fclose(sizetoget);
return fileLength;
}