尝试写入日志文件时权限被拒绝

时间:2013-03-28 16:48:25

标签: c windows file permissions fopen

我在C / C ++ prog中写入日志文件时遇到问题。 以下是发生问题的代码示例

EnterCriticalSection(&critical);
printf("\nWaiting for a connection on TCP port %d (nbr of current threads = %d)...\n", pServer->TCPServerPort, (*pServer->lChildInfo));
AddLog("Waiting for a connection on TCP port %d (nbr of current threads = %d)...", pServer->TCPServerPort, (*pServer->lChildInfo));
LeaveCriticalSection(&critical);

// creating variables to be passed to the thread
struct*ThreadData = (struct*) malloc(sizeof(struct));
ThreadData->csock = (int*)malloc(sizeof(int));
memcpy(&ThreadData->pServer,&pServer,sizeof(pServer));

if((*ThreadData->csock = accept( pServer->ListenSocket, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){

    ThreadData->dwIP = sadr.sin_addr.s_addr;
    ThreadData->wPort = sadr.sin_port;

    printf("Received connection from %s:%d \n",inet_ntoa(sadr.sin_addr), ntohs(sadr.sin_port));
    AddLog("Received connection from %s:%d ",inet_ntoa(sadr.sin_addr), ntohs(sadr.sin_port));

AddLog是我写的函数,用于写入文件:

FILE *fichier = NULL;
va_list ap;
va_start(ap, log); 
//fichier = fopen("log.log","a");
fichier = _fsopen("log.log", "a", SH_DENYNO);
if (fichier == NULL)  
    printf("Error log: %d (%s)\n", errno, strerror(errno));
else {  
    fprintf(fichier,":");
    vfprintf(fichier, log, ap);
    fprintf(fichier,"\n");
    va_end(ap);
    fclose(fichier);    
}

我无法解释的是,第一个AddLog(“Waiting for ....”和之前的所有......)都正确写入文件。但是,当我尝试连接时,那时的日志(从......接收连接)不会写入文件,我总是得到错误13“权限被拒绝”。 我使用chmod 777进入文件,我也尝试了_fsopen函数,一旦进入线程我仍然会收到此错误。 如果有人知道这将是真正有用的。 感谢所有

2 个答案:

答案 0 :(得分:0)

我不知道究竟是不是问题,但我建议在_fsopen中使用“a +” for shared append因为线程另一个进程。

答案 1 :(得分:0)

我不知道它是否仍然相关,但我不得不建议你使用更好的解决方案: (前几天我遇到了同样的问题,解决方案不仅仅是微不足道的) 我刚刚实现了一个共享队列以及我添加到队列中的所有日志,之后我运行了一个正在检查队列的工作线程,并且如果队列不为空则正在写入该文件。

我希望它有一个美好的一天:)

相关问题