Click here to Skip to main content
15,902,114 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm coding something about parsing text of which based on the logging text written by the target application on windows platform. In order to fetch specified text and make it work, I do this by the following steps:
1. Copy the target logging file to my parse folder
2. Read the logging text from my folder
3. Parse and some sh*t like that.

In step 1. the copy-file process by win32 api `CopyFile` may failed with errorcode 32 , and yes you can see that which means the target file has been occupied by the application.

So my question is there anyway to access the content of the file in some way ?
I mean , when the application was running , I use notepad.exe to open the logging text file , it never failed. I'm sure there must be a way to do this!
How to do this ?

What I have tried:

My copy-file code chunks like this :
C++
int ArchiveLogFiles(pLoger loger) {
    char archive_path[MAX_PATH]={0};
    GetCurrentDirectory(MAX_PATH,archive_path);
    strcat(archive_path,"\\Archives");
    DWORD att=GetFileAttributes(archive_path);
    if((att&FILE_ATTRIBUTE_DIRECTORY)!=0) CreateDirectory(archive_path,NULL);
    
    strcat(archive_path,"\\");
    char exists_file[MAX_PATH]={0};
    sprintf(exists_file,"%s%s",loger->folder,loger->file);
    
    char archive_file[MAX_PATH]={0};
    sprintf(archive_file,"%s%s",archive_path,loger->file);
    if(0!=CopyFile(exists_file,archive_file,FALSE)) {
        memset(loger->folder,0x00,sizeof(loger->folder));
        strcpy(loger->folder,archive_path);
        
        return 0;
    } else {
        char error_msg[1024]={0};
        DWORD error=GetLastError();
        LPSTR lpMsgBuf=NULL;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
                      NULL,error,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPSTR)&lpMsgBuf,
                      0,NULL);
        
        sprintf(error_msg,"拷贝文件\n[%s]\n至\n[%s]\n失败(%d-%s)!",exists_file,archive_file,error,lpMsgBuf);
        LocalFree(lpMsgBuf);
        SendMessage(GMAJOR->major_hwnd,MSG_HINT,(WPARAM)error_msg,(LPARAM)0);
        
        if(loger->innerCode==DXWORKER||
           loger->innerCode==MAIN_TXT||
           loger->innerCode==CORELOG) {
            /*
             * 核心文件拷贝异常
             * 需要补救
             */
            
        }
        
        return -1;
    }
}


If I open the target logging file directly without copy, also failed:
C++
int loadfile(char* filename,char** mem_ref,size_t* psize) {
    *psize=0;
    *mem_ref=NULL;
    int result=0;
    HANDLE hFile=CreateFile(filename,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    if(hFile==INVALID_HANDLE_VALUE) {
        DWORD error=GetLastError();
        LPSTR lpMsgBuf=NULL;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
                      NULL,error,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPSTR)&lpMsgBuf,
                      0,NULL);
        
        printf("打开文件[%s]失败,%d-%s\n",filename,error,lpMsgBuf);
        LocalFree(lpMsgBuf);
        return -1;
    }
    
    *psize=GetFileSize(hFile,NULL);
    
    char* buffer=(char*)calloc(sizeof(char)*((*psize)+1),1);
    if(buffer==NULL) {
        printf("内存分配异常: 分析文件 [%s] 失败。\n",filename);
        CloseHandle(hFile);
        return -1;
    }
    
    DWORD bytesRead=0;
    if(!ReadFile(hFile,buffer,*psize,&bytesRead,NULL)) {
        result=-1;
        *psize=0;
        printf("读取文件[%s]内容失败,%d\n",filename,GetLastError());
    } else {
        *psize=bytesRead;
        *mem_ref=buffer;
    }
    
    CloseHandle(hFile);
    return result;
}
Posted
Comments
CPallini 10-May-24 5:03am    
I guess it is the CopyFile destination file (not its source) the culprit (e.g. it is open in your application).
You could easily verify the above assumption.
Yount_0701 10-May-24 5:17am    
um, It's something like this
Program A writes logging text files which is a binary file programed by someone and work on my computer. I'm now using program A and I want to analysis the logging text and do something else when program A was running. Program A is using the logging file for sure and I open these files again which cause the culprit.
Yount_0701 10-May-24 5:20am    
My purpose is to parse the logging text generated by program A while it's working. I'm hoping there is a proper method to re-open the logging files while program A is just writing these files.
CPallini 10-May-24 5:25am    
I am suggesting that CopyFile fails because it cannot overwrite the destination file. It should have no problems with the source (A) file.
Yount_0701 10-May-24 5:43am    
uh, could I tell that even if the source file in use `CopyFile` will not fail, only the destination file may cause this trouble ?
If so, I have to assume my logic problems , maybe my `CopyFile` operations did too offen which the previous procedure not done yet , new `CopyFile` comes.
After code checking , that's not supposed to happen , all `CopyFile` operations have been done in one single thread one by one , no chance happend concurrently.

1 solution

So, CopyFile is a none-blocking file on the read operation. That can't be the underlying issue; you must be hitting an issue with the write part. Are you attempting to overwrite an existing file, or are you attempting to copy from a UNC file which has some weird side effects?

Your CreateFile version isn't going to work if you don't match the share mode of the application that's owns that file. You might find a combination of FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE works for you. From the documentation[^]:

You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. CreateFile would fail and the GetLastError function would return ERROR_SHARING_VIOLATION.
 
Share this answer
 
Comments
Yount_0701 10-May-24 6:01am    
`That can't be the underlying issue; you must be hitting an issue with the write part.`
Thank you , that's a confirm, I like this kind of talk . @Pete O'Hanlon and @CPallini
If so , something was wrong with my coding logic. I'm gonna to figure it out.
Pete O'Hanlon 10-May-24 6:13am    
Good luck with that. It's always good to bounce ideas off others.
Yount_0701 11-May-24 7:37am    
I tested and figured out that `That can't be the underlying issue; you must be hitting an issue with the write part.` as you said before was NOT CORRECT.
If you open file with zero-share-mode and not close the file handle, you tried to open the same file again somewhere or other process , you will meet the ERROR_SHARING_VIOLATION issue. Even if you use `CopyFile` function , the problem would be the same because copy file also need to open the file. If you use windows notepad to open the same file before the file handle was closed , same warnings would popup. And Yes I tested. The File System restrict that kind of operations. You need to close the file handle first and then re-open it, or you should not use zero-share-mode.
CPallini 10-May-24 6:10am    
5.
Pete O'Hanlon 10-May-24 6:12am    
Thank you so much young sir.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900