返回首页

嗨,我宁愿在C,但在Java的编程基本的了解。现在我试图从磁盘读取数据的问题。从文件中读取的字节数后,我通过malloc分配内存,并创建一个新的字符串来存储数据从文件中的字符串。然后,我删除空格和尝试创建的字节数组,但是它崩溃时是无效的字符

这是数据我readingfile.dat的字符串

10 02 01 02 03 04 0a 00 03 10

转换方法的字节数组
{C}
我读文件的方法

unsigned long ReadFromDisk()

{

 

	FILE	*pFile;

	long	lSize;

	char	*pCharbuff;

	

	byte	abBuffer[128];

	

	pFile = fopen ( "W:\\SW\\readingfile.dat" , "rb" );

 

	fseek(pFile , 0 , SEEK_END);

	lSize = ftell (pFile);

	rewind(pFile);

 

	// allocate the buffer

	pCharbuff = (char*) malloc (sizeof(char)*lSize);

 

// problem is here, the file has only 29 bytes of data and yet it allocates extra 4 bytes, and when checking bytes if it is a digit or not, it gives an error

	fread (pCharbuff,1,lSize,pFile);

 

// sorry forgot this line

std::string strString(pCharbuff);

 

	// remove white spaces

	bool spacesLeft = true;

	std::string::size_type pos = 0;

	while(spacesLeft)

	{

		pos = strString.find(" ");

		if(pos != std::string::npos)

			strString.erase( pos, 1 );

		else

			spacesLeft = false;

	}

 

	unsigned char* array = NULL;

	int size;

	string_to_bytearray(strString, array, size);	

 

	return 0;

}

此外,我想实现一个线程,所以我可以阅读从现在的位置,我每次离开过。我该怎么办?我可以设置下FSEEK抵消一些呢?

回答

评论会员:理查德MacCutchan 时间:2012/02/06
{C3的}
你字符串变量strString的尚未初始化缓冲区的内容从文件中读取。
[更新]
问题是你有没有终止您的输入数据,所以正确的strString(pCharbuff);构造捡垃圾。更改代码如下:
{的C4}[/更新]
评论会员:游客 时间:2012/02/06
|Stefan_Lang:你写的:{C5的}imgsrc=]:对于文本流,价值是不能保证是从文件的开头确切字节数我不知道这意味着自己,但是这可能是由于控制字符是不可见的行结束,在一个文本文件,如文件结束,等等。如果是这样的话,那么消除空间将不会有足够的-你可能还需要消除其他空白字符要删除所有的空格,你可以尝试:{5233}(见{A1}])