问一下一下本人这边为什么fopen()总在第509次的时候崩溃

C++语言 码拜 8年前 (2016-05-12) 909次浏览
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <sstream>
#include <math.h>
#define MAX_OBJ_NUM 6
using namespace std;
string ConstructFileName(string path, int filenum, string filetype)
{
	string currentnum;
	stringstream ss;
	ss.clear();
	ss << filenum;
	ss >> currentnum;
	return (path + currentnum + filetype);
}
int main()
{
	int out[4 * MAX_OBJ_NUM];
	int FirstFileNum = 1;
	int temp;
	int count = 0; 
	FILE* fp;
	for (int i = 0; i < 1018; i++)
	{
		string File = ConstructFileName("E:\workspace\Rect_out\666\", FirstFileNum, ".txt");
		fp = fopen((char*)File.data(), "r");
		if (fp == NULL)
			printf("Open %s fail!\n", (char*)File.data());
		else cout << "open" << File << endl;
		count = 0;
		while (1 == fscanf(fp, "%d ", &temp))
		{
			out[count] = temp;
			count++;
		}
                /*...*/
		fp = NULL;
		FirstFileNum++;
	}
	fclose(fp);
	system("pause");
	return 0;
}

E:\workspace\Rect_out\666\ 下面存着以数字命名的1-1018个txt文件,txt里面存着4*6=24个整数,每次运行到第510次的时候都原因是stream!=NULL崩溃,验证过txt文件没有问题,文件名路径也正确,就是读入不了,510又不是512这样的2的几次方,实在想不出原因来,还望各位前辈能指点一下。

解决方案

10

fp = NULL;
fclose(fp); 位置互换一下试试?
你这么多文件没关闭,居然没出错,也是很厉害的

30

你在for里面fopen, 在外面fclose?
匹配吗?
另外建议把fp放在for里面, 保持良好的作用域编码规范

30


fp = NULL;
改成
fclose
C/C++没有GC, 必须手动释放资源, 置空没用, 只是清空变量而已

20

文件句柄的可打开个数,由一个系统参数控制,open files
http://blog.csdn.net/hejinjing_tom_com/article/details/38760233

20

28 行:fp=NULL
44行改成:fclose(fp);fp=NULL
48行:删掉

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明问一下一下本人这边为什么fopen()总在第509次的时候崩溃
喜欢 (0)
[1034331897@qq.com]
分享 (0)