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

标签 c windows file permissions fopen

我在写入 C/C++ 程序中的日志文件时遇到问题。 下面是出现问题的代码示例

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(“等待......”和之前的所有......)已正确写入文件。但是当我尝试连接时,随后出现的日志(从...接收连接)没有写入文件,我总是收到错误 13“权限被拒绝”。 我在文件中使用了 chmod 777,我也尝试了 _fsopen 函数,但进入线程后仍然出现此错误。 如果有人有任何想法,那将非常有帮助。 感谢大家

最佳答案

我不知道这是否是问题所在,但我建议在 _fsopen 中使用“a+” 对于共享追加,因为线程另一个进程。

关于c - 尝试写入日志文件时权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687604/

相关文章:

c - 返回语句、值——它们是如何使用的?

c - 如何在C中的文件的不同位置写入字符串

windows - checkout 标签时出现 Cygwin、Git、win32 错误

c++ - 取消WIN32线程池中计划的work/io/timer项

c++ - 运行时库只是一些动态链接的库文件吗?

file - 如何使用 go in lambda 安全地检查 S3 存储桶中是否存在文件?

c - 删除C BST中的节点

c - 将异常数组归零

file - Ant,(覆盖)写入文件

php - 在 PHP 中,在使用 fopen() 将文件指针资源分配给变量后,如何从变量中获取文件名?