I am using Mathematica 10.3.1.0 on a Raspberry Pi. I would like Mathematica to open, read from, write to and close a file which may sometimes also be accessed by some external software. I created the file "dead_letter_box.txt" in "Text Editor", saved it and closed the Text Editor. The following code then worked exactly as expected:
compactreadfile[filename_, fileextension_] :=
Module[{filelocation, file, contentsoffile},
filelocation = FileNameJoin[{NotebookDirectory[], StringJoin[filename, fileextension]}];
contentsoffile = {};
If[FileExistsQ[filelocation],
file = OpenRead[filelocation];
contentsoffile = ReadList[file];
Print[contentsoffile];
Close[file];,
Print["The file does not exist"]
]
]
compactwritefile[filename_, fileextension_, contentsoffile_] :=
Module[{filelocation, file},
filelocation = FileNameJoin[{NotebookDirectory[],StringJoin[filename, fileextension]}];
If[FileExistsQ[filelocation],
file = OpenWrite[filelocation];
Write[file, contentsoffile];
Close[file];,
Print["The file does not exist"]
]
]
filename = "dead_letter_box";
fileextension = ".txt";
compactreadfile[filename, fileextension]
filename = "dead_letter_box";
fileextension = ".txt";
variable = 7;
compactwritefile[filename, fileextension, variable]
filename = "dead_letter_box";
fileextension = ".txt";
compactreadfile[filename, fileextension]
That is, the first read produced the output {}, the write produced no ouput, and the second read produced the output {7}. Moreover, when I opened the text file in the Text Editor, it contained the single character 7, as expected.
My problem is that these tests give exactly the same results, when I leave the text file open in the Text Editor. I had hoped Mathematica would return an error message, to the effect that the file is already in use by another program.
Is there a way to make Mathematica generate such errors ?