我有一个程序可以记录来自串口的数据。每隔一段时间,我想拆分文件,这样数据日志就不会变得很大。问题是,在我重新创建 FILE* 并尝试写入它之后,程序崩溃了。手头也没有编译器错误/警告......
该程序确实会在第一个时间间隔内创建一个日志,但是一旦到了创建新数据日志的时间,它就会在 fwrite 处崩溃。
首先,初始化/声明。
char * DATA_DIR = "C:\DATA";
sprintf(path,"%s%s%s",DATA_DIR,curtime,".log"); //curtime is just the current time in a string
FILE * DATA_LOG = fopen(path, "wb+");
然后在 while 循环中
if(((CURRENT_TIME-PREVIOUS_TIME) > (SEC_IN_MINUTE * MINUTE_CHUNKS) ) && (MINUTE_CHUNKS != 0) && FIRST_TIME == 0) //all this does is just checks if its time to make a new file
{
fclose(DATA_LOG); //end the current fileread
char * path;
char curtime[16];
//gets the current time and saves it to a file name
sprintf(curtime , "%s" , currentDateTime());
sprintf(path,"%s%s%s",DATA_DIR,curtime,".log");
DATA_LOG = fopen(path, "wb+"); //open the new file
//just some logic (not relevant to problem)
PREVIOUS_TIME = CURRENT_TIME;
newDirFlag = 1;
}
fwrite(cdata , sizeof(char) , numChars , DATA_LOG); //crashes here. cdata, sizeof, and numChars don't change values
知道为什么会这样吗?我很难过。
最佳答案
几个问题,路径没有分配内存(你正在向一些随机内存地址写入内容,这是错误的)。您还应该检查 fwrite
fopen
的返回值是否有错误。如果有一个使用 perror
那么你就知道问题出在哪里了。可能是 fopen 失败了,或者您通过写入 path
破坏了您的堆栈。
同时使用 snprintf
它比 sprintf
更容易受到缓冲区溢出的影响。
编辑:刚刚看到您的评论说它是 C++。为什么不使用 std::string
和 fstream
呢?它们比您目前正在做的事情更安全(并且可能更容易)。
关于c++ - 写入多个文件的 fclose、fopen 和 fwrite 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345861/