[英]C code to write a simple Flat file on server
我有以下C代码,它将向我发送电子邮件通知以获取错误消息。
现在我要寻找的是,在Unix服务器本身上为所有这些错误消息创建一个平面文件。
/* write the formatted message to the temp email file and close the file.
*/
fputs(szEmailMsg, fpTmpMsgFile);
if (ferror(fpTmpMsgFile)) {
dce_dbgwrite(DCE_LOG_ERROR,
"Child %d: write to %s for email message failed: %s", iThisChild,
pszTmpMsgFile, strerror(errno));
dce_dbgwrite(DCE_LOG_ERROR, "Child %d: email message = <%s>",
iThisChild, szEmailMsg);
return;
}
fclose(fpTmpMsgFile);
/* email the message and remove the temp email file.
*/
sprintf(szCmd,
"/usr/bin/mail -s\"lg_a17_srvr error\" %s < %s",
pszSupportAddr, pszTmpMsgFile);
if (system(szCmd) != 0) {
dce_dbgwrite(DCE_LOG_ERROR,
"Child %d: command to email error message failed: %s", iThisChild,
strerror(errno));
dce_dbgwrite(DCE_LOG_ERROR, "Child %d: email command = %s", iThisChild,
szCmd);
dce_dbgwrite(DCE_LOG_ERROR, "Child %d: email message = <%s>",
iThisChild, szEmailMsg);
}
remove(pszTmpMsgFile);
}
此pszTmpMsgFile文件包含这些信息,想要在其可移动的位置之前添加代码以创建新文件名(如>> error.log),其中包含该文件的所有信息并将其发送到不同的Unix目录...说:home / bin / letgen预先感谢!
您没有提供足够的详细信息让我确切地了解您的代码在做什么(例如, dce_dbgwrite()
做什么?它是否写入文件?数据库?)。 没有这些信息,我无法完全回答您的问题,但是对于我想问的问题,我将保留以下示例。
如果我正确理解了您的问题, szEmailMsg
将错误字符串szEmailMsg
写入名为error.log
的错误文件error.log
。 您还希望日志存在于两个位置。
以下函数将字符串附加到文件中。 如果文件不存在,将创建它。
#include <stdio.h>
void append_data_to_file(const char* path, const char* data)
{
// Open the file to append data, creates file if it does not exist.
FILE f = fopen(path, "a");
// Only continue if the previous statement succeeded
if (f != NULL)
{
// Write (append) the data to the file
fputs(data, f);
// Close the file
fclose(f);
} else {
printf("Failed to open file %s", path);
}
}
然后,您可以创建以下包装器函数来写入日志文件:
void log_error(const char* data)
{
// Write to the normal error log
append_data_to_file("error.log", data);
// Add a new line for formatting, to prevent logs from being bunched up together
// This part is optional. \n means new line.
append_data_to_file("error.log", "\n\n");
// The second location
append_data_to_file("home/bin/letgen/error.log", data);
append_data_to_file("home/bin/letgen/error.log", "\n\n");
}
要记录错误,请立即添加:
log_error(szEmailMsg);
我没有测试过任何代码 ,但是您应该大致了解该怎么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.