Comment On Fun with Files

I love file systems. You can do all sorts of neat tricks, sharing state based on file existence and naming. If it ends in ".tmp", it's not done yet. If it ends in "_hostname", that's who's handling it. I wish I could remember who said that "back in the day, they had transaction safe databases: we called them file systems." [expand full text]
« PrevPage 1 | Page 2Next »

Re: Fun with Files

2007-02-15 09:05 • by anonymouse (unregistered)
Mmmm, somehow, you'd think there'd be a better way...

Re: Fun with Files

2007-02-15 09:06 • by Mike MacDonald (unregistered)
*blink* *blink*

Zoit!

Re: Fun with Files

2007-02-15 09:07 • by snoofle
Ooooooooooooooh - destructive boolean-test functions!

Imagine the possibilities if instead of 4 characters of gibberish, it was a byte buffer of actual code?!!

Re: Fun with Files

2007-02-15 09:08 • by Cyrus (unregistered)
Narf? Oh man, my childhood memories are flooding back. What are we going to do tonight Brain?

As a side story, simply opening the file and catching the error used to be faster than checking to see if it existed on old systems, don't know how that measures up now.

Re: Fun with Files

2007-02-15 09:10 • by akatherder
The FileExists function should be named RuinFileIfItExists. Then if used properly, it is useful. Hopefully you would get a permissions error or at least a write protection error for any critical files, but you could still do a lot of damage.

Re: Fun with Files

2007-02-15 09:13 • by ParkinT
A 'catch' that does nothing but return false!

I think I will start using that in all my code; now I have a reason to USE try/catch!
</sarcasm>

Re: Fun with Files

2007-02-15 09:14 • by seconddevil
I love that pice of code, so succint and self-documenting... its so neat I think I'll include it in every new program I ever write from now on.

Re: Fun with Files

2007-02-15 09:16 • by Mikey Dub (unregistered)
Of all the things I've read on this site, that definitely qualifies as the biggest cock up. Please tell me this was discovered in QA before going live.

Re: Fun with Files

2007-02-15 09:19 • by Roy (unregistered)
Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.

Re: Fun with Files

2007-02-15 09:20 • by szukuro (unregistered)
I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

public bool FileExists(path)
{
try
{
File.Delete(path);
return true;
}
catch(FileNotFoundException){}
return false;
}

Note: fot the function to return consistent results don't call it twice on existing files :D.

CAPTCHA: onomatopoeia, now that's the real WTF

Re: Fun with Files

2007-02-15 09:20 • by snoofle
120731 in reply to 120724
ParkinT:
A 'catch' that does nothing but return false!

I think I will start using that in all my code; now I have a reason to USE try/catch!
</sarcasm>

On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action. For example, say you're reading some int from the environment:


private final static int DEFAULT_VALUE_OF_X = 1024;
int xEnvtVal = DEFAULT_VALUE_OF_X;
try {
xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
} catch (Exception e) {
// not set in envt or set-value is not an int: use default value
}


Of course, setting the default value in the exception might be more obvious, but I'm not (usually) that picky.

Re: Fun with Files

2007-02-15 09:30 • by MooseBrains (unregistered)
private bool FileExists(string strPath)

{
bool exists = false;
try
{
File.WriteAllText(strPath, "narf");
exists = true;
}
catch (Exception ex) {/* do nothing */}
finally
{
/* clean up */
File.Delete(strPath);
}
return exists;
}


captcha: kungfu (Kii-aaah!)

Re: Fun with Files

2007-02-15 09:32 • by dave (unregistered)
Apart from the obvious destructiveness, the function doesn't even do what its name claims it does.

The function is "test whether I can write to this file", which most programmers (i.e., everyone except those raised on MS-DOS) is a different question to whether it exists.

Captcha: dreadlocks: alas, no. "receding hairline", actually.

Re: Fun with Files

2007-02-15 09:38 • by Fredrik (unregistered)
The really scary thing is that "if the file already exists, it is overwritten"..

(http://msdn2.microsoft.com/en-us/library/system.io.file.writealltext.aspx)

So if the file exists, the method will basically be saying 'yeah it DID exists....mwahah' :p

Re: Fun with Files

2007-02-15 09:38 • by Sum-Yun-Gai (unregistered)
ha this is hilarious.. "does this file exist?"

"I don't know, let me try writing to it.."

"Omg an exception was thrown - that means the file doesn't exist!" (hopefully)

Re: Fun with Files

2007-02-15 09:41 • by Gabelstaplerfahrer
I think this would make an interesting solution to storing information without storing them inside files:

Create a directory (this is your variable), in which you create empty files. Just name them "0" or "1", 8 files at a time. That way you can store binary data directly in the FAT or the NTFS MFT. How nice is this! And you can perform some access control by controlling the NTFS ACL or just by locking files! The correct bit order must be controlled by creation date. That way you can only store one bit per second.

Re: Fun with Files

2007-02-15 09:43 • by Hybor (unregistered)
Seeing this, the first thing that comes to my mind is OUCH!

captcha: vern - seeing through his eyes...

Re: Fun with Files

2007-02-15 09:52 • by leeg (unregistered)
120744 in reply to 120730
szukuro:
public bool FileExists(path)
{
try
{
File.Delete(path);
return true;
}
catch(FileNotFoundException){}
return false;
}


Or even:

public bool FileExists(path)
{
try
{
File.Delete(path);
}
finally
{
return false;
}
}

At least we guarantee accuracy and consistency ;-) [n.b. must be used by Administrator]

Captcha: muhahaha....does this thing have a mindreading module?

Re: Fun with Files

2007-02-15 09:55 • by Michael (unregistered)
120745 in reply to 120730
szukuro:
I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

public bool FileExists(path)
{
try
{
File.Delete(path);
return true;
}
catch(FileNotFoundException){}
return false;
}

Note: fot the function to return consistent results don't call it twice on existing files :D.

CAPTCHA: onomatopoeia, now that's the real WTF


Shouldn't that function be named "FileUsedToExist"?

Re: Fun with Files

2007-02-15 09:55 • by Benanov
120746 in reply to 120730
szukuro:
I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

public bool FileExists(path)
{
try
{
File.Delete(path);
return true;
}
catch(FileNotFoundException){}
return false;
}

Note: fot the function to return consistent results don't call it twice on existing files :D.

CAPTCHA: onomatopoeia, now that's the real WTF


non-Idempotent functions FTW.

Re: Fun with Files

2007-02-15 09:58 • by benryves
120748 in reply to 120731
snoofle:
On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
Don't even bother catching the exception object, then...

int xEnvtVal = DEFAULT_VALUE_OF_X;

try {
xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
} catch { }


That said, it's still evil.

int xEnvtVal;

if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
xEnvtVal = DEFAULT_VALUE_OF_X;
}

Re: Fun with Files

2007-02-15 10:01 • by Andrew (unregistered)
120749 in reply to 120735
dave:
Apart from the obvious destructiveness, the function doesn't even do what its name claims it does.

The function is "test whether I can write to this file", which most programmers (i.e., everyone except those raised on MS-DOS) is a different question to whether it exists.

Captcha: dreadlocks: alas, no. "receding hairline", actually.


Even in MS-DOS there is a read-only bit. I don't think MS-DOS had a way to have a write-only file.

Re: Fun with Files

2007-02-15 10:06 • by Tom (unregistered)
"narf"... Does that translate to "Not A Real File"?

Re: Fun with Files

2007-02-15 10:11 • by me (unregistered)
I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

bool is_witch(victim)
{
witch = acquire_lock(victim);
submerge(witch);
sleep(3600);
if (witch.is_dead())
return false; // not a witch; sorry
return true;
}

Re: Fun with Files

2007-02-15 10:12 • by abx
Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

Re: Fun with Files

2007-02-15 10:15 • by snoofle
120753 in reply to 120748
benryves:
snoofle:
On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
Don't even bother catching the exception object, then...

int xEnvtVal = DEFAULT_VALUE_OF_X;

try {
xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
} catch { }


That said, it's still evil.

int xEnvtVal;

if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
xEnvtVal = DEFAULT_VALUE_OF_X;
}

Hmmm, perhaps I should have stated I was writing Java code - not sure what language you responded with... syntax does vary a bit from language to langauge </smiles>

Re: Fun with Files

2007-02-15 10:16 • by snoofle
120755 in reply to 120752
abx:
Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

so the correct name of the function really should be:

createTheFileIfItDoesntExistOrTrashItIfItDoes

Nice!

Re: Fun with Files

2007-02-15 10:16 • by foo (unregistered)
120756 in reply to 120752
Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

Ever heard of that little concept called permissions?

Re: Fun with Files

2007-02-15 10:18 • by C Gomez (unregistered)
120757 in reply to 120729
Roy:
Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.


It's not. Here's why.

Many developers who are unfamiliar with Java or .NET have had to make the jump from VB or C++ because that's where their employer is taking them.

Instead of taking the time to learn the new frameworks, and even explore them a little, they jump right in. And hey, we all have to get work done, so hmm, how can I get this done?

This is what leads to this. For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty. I saw another developer create all sorts of fancy state data to make sure some code was running on the UI thread instead of just testing InvokeRequired and then doing an Invoke to make sure it was.

It's not a joke, its undereducation. There isn't an impetus from management to offer training, either. So really, if you're just punching the clock, you aren't out ahead of the curve reading about things so you're ready when you need them.

Re: Fun with Files

2007-02-15 10:19 • by snoofle
120758 in reply to 120756
foo:
Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

Ever heard of that little concept called permissions?

Yes, but when WTF-developers create files with (in UNIX-ese) permissions 777, that doesn't really help.

Re: Fun with Files

2007-02-15 10:21 • by Mikademus
I don't see the WTF, the code IS nicely indented!

Re: Fun with Files

2007-02-15 10:22 • by abx
120760 in reply to 120756
foo:
Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

Ever heard of that little concept called permissions?
Well if the .NET runtime doesn't have write permissions, then a SecurityException will be thrown when writing or creating, so the test would fail in both cases. Still doesn't make a very useful function, but granted, if there's something of some value on that file system, let us hope for their sake that the application doesn't have write permissions.

Re: Fun with Files

2007-02-15 10:26 • by SomeCoder (unregistered)
Oh dear god. Please tell me this code is a joke. Please? This is just.... gah...

And that testing for a witch code was pretty damn good :)

Re: Fun with Files

2007-02-15 10:32 • by Jens (unregistered)
Would love to see the FileReader

Example:
/snip
strContent = srReader.ReadToEnd().Replace( "narf", "" );
/snip

Re: Fun with Files

2007-02-15 10:33 • by dustin (unregistered)
120765 in reply to 120719
wow a wtf that could actually use the FileNotFound exception without trying to be funny

Re: Fun with Files

2007-02-15 10:36 • by Yeah Right (unregistered)
The person that wrote the original code is the kind of person that would leave a brick on the sidewalk under a pile of leaves.

Merrily walking along, whimsically scuffing through the leaves - OW MY FOOT!

Please schedule this person for immediate termination of some sort or another. Thank you.

Re: Fun with Files

2007-02-15 10:38 • by benryves
120767 in reply to 120753
snoofle:
Hmmm, perhaps I should have stated I was writing Java code - not sure what language you responded with... syntax does vary a bit from language to langauge </smiles>
I did think it looked a bit odd. I was going for C# as the OP is C#.

Can you try and convert a value (in Java) without throwing an exception on bad input? Maybe it's just the way .NET likes to do things, but I've always found exceptions should only be used in, well, truly exceptional cases and if there is a way to avoid them (using int.TryParse instead of int.Parse) then do so.

Re: Fun with Files

2007-02-15 10:39 • by Anonymous Bastard (unregistered)
argh. someone should be beaten up severly over this.

Re: Fun with Files

2007-02-15 10:40 • by So..... (unregistered)
120770 in reply to 120748
benryves:
snoofle:
On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
Don't even bother catching the exception object, then...

int xEnvtVal = DEFAULT_VALUE_OF_X;

try {
xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
} catch { }


That said, it's still evil.

int xEnvtVal;

if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
xEnvtVal = DEFAULT_VALUE_OF_X;
}


What do you think TryParse does....

Re: Fun with Files

2007-02-15 10:51 • by Zylon
120774 in reply to 120770
So the test destroys any existing data, eh? That's not a WTF, that just means the function is Heisenberg-compliant! As all atomic operations should be. (rim shot)

Re: Fun with Files

2007-02-15 10:54 • by David Cameron (unregistered)
120777 in reply to 120759
Mikademus:
I don't see the WTF, the code IS nicely indented!


That is only because VS.Net does that automatically.

Re: Fun with Files

2007-02-15 10:57 • by Guido (unregistered)
This is one of the happiest days in my TDWTF life...

Aside from the "onomatopoeia captcha guy", nobody started his post with "The real WTF is that... ".

Re: Fun with Files

2007-02-15 10:58 • by So..... (unregistered)
120782 in reply to 120780
The real WTF is....

Re: Fun with Files

2007-02-15 11:06 • by Bezalel (unregistered)
120785 in reply to 120780
Guido:
Aside from the "onomatopoeia captcha guy", nobody started his post with "The real WTF is that... ".


I guess I'll have to do it.

The real WTF is that the function doesn't return FILE_NOT_FOUND if it doesn't exist.

Re: Fun with Files

2007-02-15 11:13 • by Anonymous (unregistered)
120793 in reply to 120757
C Gomez:
For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty.


OK, I have to pull you up on this. Officially, the best way is to check that the string's length is zero, as that is faster than comparing to String.Empty.

Otherwise you've got a valid point, though.

Re: Fun with Files

2007-02-15 11:18 • by Poppa Vein (unregistered)
.NET System.IO.File.Exists (MS.NET 1.1) is a WTF anyway... From MSDN:

"Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."

That is, "the file may exist, but we're not going to tell ya".

Re: Fun with Files

2007-02-15 11:21 • by Ancient_Hacker
Actually, if the function was renamed "FileCanBeTrashedAndTruncatedAndWrittenTo", it would be pretty good code.

Quite often calling a FileExists() function is the wrong thing. Just knowing a file exists isnt what you want to do-- you actually want to know if the file is readable or writeable by you. Just about the only way to make sure is to try reading or writing. No, stat() just tells you what the file flags WERE a little bit in the past, not very useful right now or a nanosecond later.




Re: Fun with Files

2007-02-15 11:36 • by zlogic
120806 in reply to 120734
MooseBrains:
private bool FileExists(string strPath)

{
bool exists = false;
try
{
File.WriteAllText(strPath, "narf");
exists = true;
}
catch (Exception ex) {/* do nothing */}
finally
{
/* clean up */
File.Delete(strPath);
}
return exists;
}


captcha: kungfu (Kii-aaah!)

Here's a simpler version:
private bool FileExists(string strPath)

{
try{
File.Delete(strPath);
}
catch (Exception ex) {/* do nothing */}
return false;
}

Re: Fun with Files

2007-02-15 11:44 • by Sven (unregistered)
120810 in reply to 120793
Anonymous:
C Gomez:
For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty.


OK, I have to pull you up on this. Officially, the best way is to check that the string's length is zero, as that is faster than comparing to String.Empty.

Otherwise you've got a valid point, though.

.Net 2.0 also offers the String.IsNullOrEmpty static method, which is equivalent to doing (str != null && str.Length > 0).

And in VB.NET the compiler is smart enough to automatically replace comparisons to an empty string with something that's equivalent to that.

Re: Fun with Files

2007-02-15 11:45 • by Sven (unregistered)
120811 in reply to 120810
Sven:
.Net 2.0 also offers the String.IsNullOrEmpty static method, which is equivalent to doing (str != null && str.Length > 0).

Obviously I meant it's equivalent to (str == null || str.Length == 0).

Let's not randomly negate expression, shall we. :)
« PrevPage 1 | Page 2Next »

Add Comment