天天看點

整型數組處理算法(二)檔案中有一組整數,要求排序後輸出到另一個檔案中

如題,需要将檔案裡的一組整數,排序後寫到另外一個檔案中。

思路:

一次讀取一個sizeof(int),然後往一個int*數組裡寫入,寫入的時候就比較,進行排序。

然後,在周遊數組,寫到檔案中。

實作代碼如下:

#define READ_FILE  "C:\\tempR.txt"
#define WRITE_FILE  "C:\\tempW.txt"


/*按降序排列數組*/
int InsertData(int* a, int nValue, int nCount)
{
	for (int i=0; i<nCount; i++)
	{
		if (a[i]<nValue)
		{
			for (int j=nCount-1; j>i; j--)
			{
				a[j]=a[j-1];
			}

			a[i]=nValue;

			break;//跳出循環
		}
	}
	return 0;
}

/*寫資料到檔案*/
int WriteData(int* a,  char* pFile,int nCount)
{
	FILE* fpWrite=NULL;
	fpWrite = fopen(pFile, "wb+");
	if (fpWrite!=NULL)
	{
		for (int i=0; i<nCount; i++)
			fwrite((char*)&a[i], sizeof(int), 1, fpWrite);

		fclose(fpWrite);
	}

	return 0;
}

int ProcessData()
{
	FILE* fpRead =NULL;
	int nSize=0;
	int nTemp;
	int nCount=0;
	
	int* a50;//int* a50 = new int[];,這樣寫會導緻R6030 CRT not initialized,錯誤提示。
		     //這裡應該是記憶體沒有申請就使用了。

	fpRead = fopen(READ_FILE, "rb+");

	if (fpRead!=NULL)
	{
		fseek( fpRead, 0L, SEEK_END );
		int nRet = ftell(fpRead); 

		a50 = new int[nRet/sizeof(int)];

		fseek( fpRead, 0L, SEEK_SET );//移到檔案頭

		nSize = fread((void*)&nTemp, sizeof(int), 1, fpRead);
		while (nSize>0)
		{
			nCount++;

			InsertData(a50, nTemp, nCount);

			
			nSize = fread((void*)&nTemp, sizeof(int), 1, fpRead);
		}

		fclose(fpRead);
	}
	
	WriteData(a50, WRITE_FILE, nCount);

	delete a50;
	a50 = NULL;

	return 0;
}
           
int main()
{
/*
//可以執行這個先進行寫測試資料到檔案
	int* a=new int[10];
	for (int i=0; i<10; i++)
	{
		*(a+i)=i;
	}

	WriteData(a, READ_FILE, 10);

	delete a;
	a = NULL;
*/
	ProcessData();
	return 0;
}
           

測試結果,就不貼了,有興趣的朋友可以用代碼測試測試,檔案是按二進制寫的,用UE或其他可以檢視二進制的工具打開。

在這個過程遇到R6030 CRT not initialized的問題,才改變算法,先讀取檔案大小,計算整型數個數。關于為什麼會出現R6030 CRT not initialized另外寫一篇。

轉載請注明原創連結:http://blog.csdn.net/wujunokay/article/details/12040301

繼續閱讀