when I use MoveFileEx to move files in C drive, but I am getting the ERROR that ACCESS DENIED. Any solutions
int i ;
DWORD dw ;
String^ Source = "C:\\Folder\\Program\\test.exe" ;
String^ Destination = "C:\\test.exe"; // move to program Files Folder
pin_ptr<const wchar_t> WSource = PtrToStringChars(Source);
pin_ptr<const wchar_t> WDestination = PtrToStringChars(Destination);
i = MoveFileEx( WSource, WDestination ,MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED ) ;
dw = GetLastError() ;
You need to make sure that the user account your process runs under has read access to the file being moved and write access to where it's being written to. And that the file being moved isn't locked by another process and that there isn't a file with the same name in the destination directory that's locked by another process.
Try moving the same file manually in Windows Explorer and see what errors you get, when you can do that without problems your app will probably work too (assuming they're running under the same account).
is the code posted in your question the real used code ???
if it is so, you are having a problem with your filenames. \ is the escape character in C and C++ strings, it should be doubled if you want a real \ character in the resulting string.
so your pathes should be:
String source = "C:\\Folder\\Program\\test.exe";
String Destination = "C:\\test.exe";
also, ^ is not a valid character in C and C++, it is only valid for defining pointers in Pascal. i suspect your code is really written in Pascal, but then i am unsure if the above remark about the escape character in string is valid in Pascal...
Related
While researching this question I came across the fact that in POSIX (and Linux) there simply is not a truncateat system call.
Certain system calls like for instance unlink have an equivalent alternative method with an added at suffix at the end of their names, i.e. unlinkat. The difference between those methods is that the variations with the at suffix accept an additional argument, a file descriptor pointing to a directory. Therefore, a relative path passed into unlinkat is not relative to the current working directory but instead relative to the provided file descriptor (an open directory). This is really useful under certain circumstances.
Looking at truncate, there only is ftruncate next to it. truncate works on paths - absolute or relative to the current working directory. ftruncate directly works on an open file handle - without any path being specified. There is no truncateat.
A lot of libraries (various "alternative" C-libraries) do what I did and mimic tuncateat by using an openat-ftruncate-close-sequence. This works, in most cases, except ...
I ran into the following issue. It took me months to figure out what was happening. Tested on Linux, different 3.X and 4.X kernels. Imagine two processes (not threads):
Process "A"
Process "B"
Now imagine the following sequence of events (pseudo code):
A: fd = open(path = 'filename', mode = write)
A: ftruncate(fd, 100)
A: write(fd, 'abc')
B: truncate('filename', 200)
A: write(fd, 'def')
A: close(fd)
The above works just fine. Just after process "A" has the file opened, set its size to 100 and written some stuff into it, process "B" re-sets its size to 200. Then process "A" continues. At the end, the file has a size of 200 and contains "abcdef" at its beginning followed by zero-bytes.
Now, let's try and mimic something like truncateat:
A: fd_a = open(path = 'filename', mode = write)
A: ftruncate(fd_a, 100)
A: write(fd_a, 'abc')
B: fd_b = openat(dirfd = X, path = 'filename', mode = write | truncate)
B: ftruncate(fd_b, 200)
B: close(fd_b)
A: write(fd_a, 'def')
A: close(fd_a)
My file has a length of 200, ok. It starts with three zero-bytes, not ok, then the "def", then then again zero-bytes. I have just lost the first write from process "A" while the "def" technically landed at the correct position (three bytes in, as if I had called seek(fd_a, 3) before writing it).
I can work with the first sequence of operations just fine. But in my use case, I can not rely on paths relative the current working directory as far as process "B" is concerned. I really want to work with paths relative to a file descriptor. How can achieve that - without running into the issue demonstrated in the second sequence of operations? Calling fsync from process "A" just after write(fd_a, 'abc') does not solve this.
The reason why your second case overwrites everything with zeroes is that mode=truncate (i.e. openat(.., O_TRUNC)) will first truncate the file to length 0.
If you instead ftruncate to 200 immediately without first truncating to 0, the existing data up until that point will remain untouched.
currently, what happens in windows explorer when highlighting and batch renaming files/folders is as such:
test(1).jpg
test(2).jpg
test(3).jpg
how do i code a script such that highlighting the files/folders and hitting the same hotkey (f2) allows me to change the naming convention?
Variable {space} ###.jpg
where Variable is the name for user input and ### is the running sequence starting from 001?
in addition, i need the script to IGNORE warnings when there's already another file with the previous same name. one possible way to overcome this is to temporarily rename the offending file to a temp name first, so that the renamer can continue with its correct sequence.
Yes, i do know there are many capable applications that can already do the simple job above - but i prefer NOT to have a GUI (since it's v simple).
appreciate everyone's help!
consider this example :
#Include Explorer.ahk ;get it from : https://github.com/denolfe/AutoHotkey/blob/master/lib/Explorer.ahk
F2::
InputBox, Variable, Rename files, Enter your filename prefix.,, 250, 150,,,,,DefaultPrefix
path := Explorer_GetPath()
sel := Explorer_GetSelected()
MsgBox % sel
if ( StrLen(sel) && FileExist(path) )
{
Loop, Parse, sel, `n
{
SetWorkingDir, %path%
MsgBox %A_loopfield%
FileMove, %A_loopfield%, %Variable%_%A_index%.*, 1 ; the '1' means Overwrite
}
}
return
I am using COPY to copy a field from a table to a file. this field is a zipped text file, so I use a binary copy.
the file is created, the only problem is that COPY adds a header and a trailer (?) to the file, which I don't need. can this be changed? is there a parameter that can cause COPY to put the field exactly as it is in the database?
If I manually delete the unwanted header I can extract the file with zcat, or gunzip.
I am doing somthing like this:
psql -d some_database -c \
"copy (select some_column from a_table where id=900) to stdout with BINARY;" > /tmp/tmp.gz
And then I want to do
gunzip /tmp/tmp.gz
Any ideas?
One possibility, which works although you may not like it:
psql -At -c "select encode(content, 'base64') from t where ..." | base64 -d
i.e. print the content as base64 and decode it. I think the reality is that psql is intended to produce readable output, and persuading it to disgorge raw binary data is intentionally difficult.
I suppose if you want to enough, you can write some tool (Perl/python script) to connect to the database and print raw output directly.
The "WITH BINARY" option to COPY doesn't just do a simple binary output, it performs some encoding which is probably dubious to rely on.
Are your sure it's best way to store zipped text in database as binary ? According to documentation long text is implicitly/automatically compressed:
Long strings are compressed by the
system automatically, so the physical
requirement on disk might be less.
Very long values are also stored in
background tables so that they do not
interfere with rapid access to shorter
column values. In any case, the
longest possible character string that
can be stored is about 1 GB.
I don't know a straightforward way... COPY has a binary format with a variable length header, not very easy to "trim". Outside that, PG is rather text-centric, I don't tkink there is way to force an "raw" (binary) output from a SELECT for a BYTEA field.
You could get a textual hexadecimal output and write yourself a little program (C, perl or whatever) to convert it from say \x000102414243 to binary. Not difficult, but not straightforward (and the hex format is in Postgresql 9.0)
psql -t -q -c "select binaryfield from.. where ..." mydb | myhextobin > tmp.gz
BTW, Grzegorz's answer is very pertinent.
Added: not very clean, nor foolproof, just if something finds it useful...
/* expects a pg hexadecimal string, in "\x....." format, and converts to binary*/
/* warning: no checks! it just ignores chars outside [0-9a-f] */
#include<stdio.h>
int main() {
int x, pos, v;
char hex[3]={0,0,0};
pos = 0;
while( (x = getchar()) >= 0) {
if(( x >='0' && x <= '9') || ( x >= 'a' && x <= 'f' )) {
hex[pos++] = (char)x;
if(pos == 2) {
sscanf(hex, "%x", &v);
putchar((char)v);
pos = 0;
}
}
}
return pos==0 ? 0 : 1;
}
The copy command do the job. You only need to tell: --no-align and --tuples-only.
For compression, use gzip between psql and file
psql --tuples-only --no-align -d some_database -c \
"copy (select some_column from a_table where id=900) to stdout with BINARY;" | gzip > /tmp/tmp.gz
It is not suggested to attempt to decode the postgresql binary format. Just because the test file you are using works doesn't mean everything will work. For instance, perhaps certain character sequences (not appearing in your test file) get escaped.
You may find it easier to do this by using a language that has client drivers and the ability to read the bytea type: PHP, python, ruby, perl, javascript, java, etc. Just perform your query there, use gzip libraries that probably already exist in that language, and write out the file.
Alternately, you could use a procedural language inside the database and create a stored procedure. You would pass the requested filename to the stored procedure.
I'm trying to check if a folder has any subfolders without iterating through its children, in Linux. The closest I've found so far is using ftw and stopping at the first subfolder - or using scandir and filtering through the results. Both, are, however, an overkill for my purposes, I simply want a yes/no.
On Windows, this is done by calling SHGetFileInfo and then testing dwAttributes & SFGAO_HASSUBFOLDER on the returned structure. Is there such an option on Linux?
The standard answer is to call stat on the directory, then check the st_nlink field ("number of hard links"). On a standard filesystem, each directory is guaranteed to have 2 hard links (. and the link from the parent directory to the current directory), so each hard link beyond 2 indicates a subdirectory (specifically, the subdirectory's .. link to the current directory).
However, it's my understanding that filesystems aren't required to implement this (see, e.g., this mailing list posting), so it's not guaranteed to work.
Otherwise, you have to do as you're doing:
Iterate over the directory's contents using glob with the GNU-specific GLOB_ONLYDIR flag, or scandir, or readdir.
Call stat on each result and check S_ISDIR(s.st_mode) to verify that files found are directories. Or, nonportably, check struct dirent.d_type: if it's DT_DIR then it's a file, and if it's DT_UNKNOWN, you'll have to stat it after all.
The possibilities you've mentioned (as well as e.James's) seem to me like they're better suited to a shell script than a C++ program. Presuming the "C++" tag was intentional, I think you'd probably be better off using the POSIX API directly:
// warning: untested code.
bool has_subdir(char const *dir) {
std::string dot("."), dotdot("..");
bool found_subdir = false;
DIR *directory;
if (NULL == (directory = opendir(dir)))
return false;
struct dirent *entry;
while (!found_subdir && ((entry = readdir(directory)) != NULL)) {
if (entry->d_name != dot && entry->d_name != dotdot) {
struct stat status;
stat(entry->d_name, &status);
found_subdir = S_ISDIR(status.st_mode);
}
}
closedir(directory);
return found_subdir;
}
Does getdirentries do want you want it to do? I think it shoudl return nothing if there are no directories. I would have tried this myself but am temporarily without access to a linux box :(
I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode).
How would I get a unique Process ID and Thread ID in Delphi?
Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?
Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames
you have many good ideas presented here.
Does it also create an empty file to "get a lock on" the name?
no; i believe we rely on Windows to ensure the same temp file name is never given twice on the same computer since boot time.
is there any chance of a clash if there is a split second delay between generating the name and creating the file (if I need to create the file myself).
no; that'd be a pretty bad thing.
here's a routine i've been using for getting a temp file.
function GetTemporaryFileName:string;
var
Path, FileName: array[0..MAX_PATH] of Char;
begin
Win32Check(GetTempPath(MAX_PATH, Path) <> 0);
Win32Check(GetTempFileName(Path, '~EX', 0, FileName) <> 0);
Result:=String(Filename);
end;
you could instead use FileGetTempName( ) from JclFileUtils.pas in JCL.
Windows provides functionality for creating guaranteed unique file names. No need for creating your own:
Here's a Delphi wrapper around that functionality:
function CreateTempFileName(aPrefix: string): string;
var
Buf: array[0..MAX_PATH] of Char;
Temp: array[0..MAX_PATH] of Char;
begin
GetTempPath(MAX_PATH, Buf);
if GetTempFilename(Buf, PChar(aPrefix), 0, Temp) = 0 then
begin
raise Exception.CreateFmt(sWin32Error, [GetLastError, SysErrorMessage(GetLastError)]);
end;
Result := string(Temp);
end;
Could you not use a GUID instead?
Edit: Should have said first time around, check out the following two functions
CreateGuid
GuidToString
Process IDs are not guaranteed to be unique on windows. They are certainly unique for the life of the process, but once a process dies its id can be immediately reused. I am not certain about ThreadIDs. If these are temporary files you could use something equivalent to tmpfile or tmpnam (C functions, but I assume Delphi has an equivalent).
As Jamie posted a GUID may be better.
1) How to get a unique Process ID & ThreadID in Delphi:
Answer:
NOTE: Ensure to add 'windows' to your uses clause in the implementation section
NOTE: Cardinals are unsigned 32-bit integers ranging from 0 to 4294967295
implementation
uses Windows;
procedure MySolution();
var
myThreadID:Cardinal;
myProcessID:Cardinal;
begin
myThreadID := windows.GetCurrentThreadID;
myProcessID := windows.GetCurrentProcessId;
end;
2) Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?
Answer: Yes.
The process identifier is valid from
the time the process is created until
the process has been terminated and is
unique throughout the system. (Not
unique to processor)
Until the thread terminates, the
thread identifier uniquely identifies
the thread throughout the system.
(Again, system wide, not unique to
processor)
Better than either of of those options, you should be using the system function _tempnam. It returns a random file name in the directory for a file that does not exist. If you want to, you can supply a prefix to _tempnam so that the file you create is recognizably yours. If you are providing a unique prefix, there is shouldn't be any worry about someone opening your file. There is another solution, however.
_tempnam is only good if you want to put the file into an arbitrary directory. If you don't care that the directory is the system temporary directory, use tempfile_s instead. It will also create the file for you, so no worry about race conditions... Errors will only occur if you try to open more temp files than the system can handle. The big downside to tempfile_s is that the file will disappear once you fclose it.
EDIT: I've gotten a downvote because this is a C function. You have access to the C runtime by importing them into delphi. Have a look at some examples with msvcrt.dll here.
function _tempnam(const Dir: PChar, const Prefix: PChar): PChar; cdecl;
external 'msvcrt.dll' name '_tempnam';
Others all gave you a good and reasonable ideas, but still - if you're using files for temporary storage and if those files will always be created first (it doesn't matter if there is a leftover file with a same name already on the disk as you'll overwrite it anyway) then processid_threadid approach is completely valid.
Use GetCurrentProcessID and GetCurrentThreadID Win32 calls to access those two IDs.