How to add copy to filename if already exists? - objective-c

Is there a way for if a file already exists (say /hello.txt) and you run the command:
[data writeToFile:#"/hello.txt" atomically:YES];
Instead of overwriting create the file hello copy.txt and then hello copy 2.txt as finder does naturally?

First, you need to use a data-writing method that will refuse to overwrite an existing file. You can use -[NSData writeToFile:options:error:] with the option NSDataWritingWithoutOverwriting. Check its return value to see if it failed and then check the returned NSError to see if the reason it failed was an existing file. If it is, build a new path string based on the original and the number of tries you've made, adding either " copy" or " copy %u", and loop around to try again. Stop looping if you succeed or you get any other error. (You might also put a limit on the maximum number of tries, in case something unforeseen happens.)
The NSError indicates a failure because a file already exists at that path if its domain is NSCocoaErrorDomain and its code is NSFileWriteFileExistsError.

Related

How to ignore failure when file does exist when downloading with WinSCP script

Running a script to get a file from SFTP server, however this is recurring job and should still succeed if no file exist, is there an option I can specify?
option batch on
option confirm off
option transfer binary
open sftp://server -timeout=60
password
get /File/2_04-28-2015.txt D:\Files
close
exit
Getting this result:
Can't get attributes of file 'File/2_04-28-2015.txt'.
No such file or directory.
Error code: 2
Tried setting failonnomatch:
winscp> option failonnomatch on
Unknown option 'failonnomatch'.
You cannot tell WinSCP to ignore absent file, when using a specific file name.
But you can check the file existence prior to the actual download.
Easy alternative hack is to use a file mask (note the trailing *) and set the failonnomatch off:
option failonnomatch off
get /File/2_04-28-2015.txt* D:\Files\
(if you are getting "Unknown option 'failonnomatch'", then you have an old version of WinSCP).
Have you tried using MGET instead of GET? It shouldn't fail, just not transfer anything if there's nothing there.

Error when copy file from one place to another in NSFileManager

When I use NSFileManager to copy one file (directory) from one place to another by using copyItemAtPath, it gives me error.
Here is the code:
[[NSFileManager defaultManager]copyItemAtPath:#"/Users/name/Documents/localhost/websiteDesign/_Software/" toPath:#"/Volumes/NAME/" error:&handleError];
NSLog(#"%#", [handleError description]);
Here is the error:
Error Domain=NSCocoaErrorDomain Code=516 "“_Software” couldn’t be copied to “Volumes” because an item with the same name already exists." UserInfo=0x102842d00
{NSSourceFilePathErrorKey=/Users/name/Documents/localhost/websiteDesign/_Software/, NSUserStringVariant=(Copy), NSDestinationFilePath=/Volumes/NAME/, NSFilePath=/Users/name/Documents/localhost/websiteDesign/_Software/, NSUnderlyingError=0x10283f8e0 "The operation couldn’t be completed. File exists"}
However, when I change the name of the destination file which is #"/Volumes/NAME/", to whatever else like #"/Volumes/aaa/", then the error will gone. I do not know why. Thanks !!
You need to specify the full pathname, including the actual filename.
Apple's documentation for copyItemAtPath:toPath:error: states, for the "toPath:" parameter:
The path at which to place the copy of srcPath. This path must
include the name of the file or directory in its new location. This
parameter must not be nil.
What you're doing right now is trying to overwrite an entire hard drive (volume) with a file.

CFSCRIPT - How to check the length of a filename before uploading

I ran into this problem when uploading a file with a super long name - my database field was only set to 50 characters. Since then, I have increased my database field length, but I'd like to have a way to check the length of the filename before uploading. Below is my code. The validation returns '85' as the character length. And it returns the same count for every different file I upload (none of which have a file name length of 85).
<cfscript>
missing_info = "<p>There was a slight problem with your submission. The following are required or invalid:</p><ul>";
// Check the length of the file name for our database field
if ( len(Form["ResumeFile1"]) gt 100 )
{
missing_info = missing_info & "<li>'Resume File 1' is invalid. Character length must be less than 100. Current count is " & len(Form["ResumeFile1"]) & ".</li>";
validation_error = true;
ResumeFileInvalidMarker = true;
}
</cfscript>
Anyone see anything wrong with this?
Thanks!
http://www.cfquickdocs.com/cf9/#cffile.upload
After you upload the file, the variable "clientFileName" will give you the name of the uploaded file, without a file extension.
The only way to read the filename before you upload it would be to use JavaScript to read and parse the value (file path) in the file field.
A quick clarification in the wording of your question. By the time your code executes the file upload has already happened. The file resides in a temporary directory on the ColdFusion server and the form field related to the file upload contains the temporary filename for that file. Aside from checking to see if a file has been specified, do not do anything directly with that file or you'll be circumventing some built in security.
You want to use the cffile tag with the upload action (or equivalent udf) to move the temp file into a folder of your choosing. At that point you get access to a structure containing lots of information. Usually I "upload" into a temporary directory for the application, which should be outside of the webroot for security.
At this point you'll then want to do any validation against the file, such as filename length, file type, file size, etc and delete the file if it fails any checks. If it passes all checks then you move it into it's final destination which may be inside the webroot.
In your case you'll want to check the cffile structure element clientFile which is the original filename including extension (which you'll need to check, since an extension doesn't need to be present and can be any length).

Problems reading local text file with [NSString stringWithContentsOfFile...] with Objective-c returns null

This does not seem so complex. I just want to create a string object with the contents of a local text file called "test.txt" which I have placed in the root of my project.
I am trying to load it w/ the following code.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"txt"];
NSString *textData = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//The below works, but not my above... not sure why.
//textData = #"TEST TEST";
NSLog(#"Some text from a file of %#", textData);
NSLog(#"The length of the string is %lu", [textData length]);
The output from this code is
"Some text from a file of (null)"
"The length of the string is 0"
I am not sure why this is returning null instead of the contents of my text file. The encoding for the file seems appropriate. Also, the file exists. Am I dragging the file to the wrong location? Do I have to add it to my NSBundle mainBundle in some way?
Thanks!
If you actually fill in the error parameter in +stringWithContentsOfFile:encoding:error: then it would tell you why it's returning nil. You really ought to do that. The likely reason is there is no file at that path (or you don't have permissions to read it).
NSLog the filePath and see if it's nil. If the filePath is nil, I think you didn't put the file in right place. You should drag the file into the project navigator of your project in Xcode.
Also, double check the file name.
Log your filePath to see if it can actually find the file, if not, you probably add your test.txt in a wrong way. To add to main bundle, drag your test.txt into your xcode project, when prompted, just tick Copy items into destination group's folder (if needed) and select Create groups for any added folders.
All of the answers here helped a little bit. In particular the suggestion to fill in the error: in a way that does not return nil.
Eventually I found that I had to manually copy the .txt file I was trying to open to the same directory as the binary that was compiled. Just copying it into the xcode project did not seem to work for me.
I was having the exact same problem as you, Vincent. My understanding is that because I am making an console-based application, it doesn't compile and include files within a bundle in the same way that an iOS app would. Therefore, it's not including the file as expected. I was able to get it to work by typing out the full directory location of the file on my hard drive.
Drag and drop your test.txt file to Build Phases->copy bundle resources

Checking for file existence

I have the following bat but it dosnt seem to work I want to check for a file name stoted in tom.txt, if it exists i want to do nothing, if however it dont exist i want to run the runme.bat
Echo Setting variable to file name
set FAT=<C:\tom.txt
ECHO Checking for file, if exists do nothing if not run bat...
if exists %FAT% (
end
)else(
C:\runme.bat
)
There are some minor mistakes, which, however, are the cause of your major difficulties.
You can read a line from a file with the SET /P command, not simply with SET:
SET /P FAT=<C:\tom.txt
The keyword in the file existence check command is EXIST, not EXISTS
IF EXIST …
Also, if you only need to react to the file's non-existence, you can simply add NOT:
IF NOT EXIST …
So, the entire command might be like this:
IF NOT EXIST %FAT% C:\runme.bat
I believe the correct syntax is
if exist %FAT% goto NORUN
C:\runme.bat
:NORUN
Notice "exist" vs "exists" in your code. A couple other things to note:
File NUL exists in any directory on any drive, therefore checking
for C:\NUL will always return true.
Checking for file existence
does not always work correctly on network devices.
See http://support.microsoft.com/kb/65994 for a bit more information.
I think the simplest solution would be to do it all on one line like this:
IF NOT EXIST C:\tom.txt C:\runme.bat
There is no need for the variable unless you intend on using it again, it just means another line of code. As Aleks G and Andriy M said, you need to make sure the commands and parameters are spelt correctly.