Question

It seems like this code should work...

set data "sample text"
set file_name "C:\Test2.txt"
set file_obj [open $file_name w]
puts -nonewline $file_obj $data
close $file_obj

But no file is created on either of my systems.

set file_name "C:\Test2.txt"
file exists $file_name

Comes back as 1 (true) while the file does not exist whatsoever. Confusing.

Était-ce utile?

La solution

The file is probably created, not in the root directory of C: but in the current directory. You see, the way the Tcl interpreter treats backslashes in a double-quoted string is to convert it and the following character to a special character (such as \t, which gets converted to a tab character, and \n, which becomes a newline). When the interpreter looks at the string "C:\Test2.txt" it finds the combination \T, which isn't a valid escape code, so it evaluates the string to just "C:Test2.txt", which is a legal file name in Windows, meaning Test2.txt in the current directory of C:.

The solution is to instead use Unix-style regular slashes in your file names, such as "C:/Test2.txt".

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top