【发布时间】:2013-08-20 22:16:59
【问题描述】:
我有一个从串口记录数据的程序。每隔一段时间,我想拆分文件以使数据日志不会变得非常大。问题是,在我重新创建 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
任何想法为什么会发生这种情况?我被难住了。
【问题讨论】:
-
你在检查fopen和fwrite等的返回值吗?
-
这是 C++ 还是简单的 C?
-
另外,声明 char * path 没有任何大小或动态分配可能会产生不必要的副作用。
-
这是用 C++ 编写的。不,我没有检查返回值。我现在就去做。
标签: c++ file-io fopen fwrite fclose