Programming/C/C++

Text 마지막에서 10줄 읽어오기

acidpop 2012. 11. 19. 15:07
반응형
long GetLastNLine(int nLastLine)
{
	int nLineCount = 0;
	char ch = '\0';
	TCHAR szBuf[8192] = _T("");
	int nResult = 0;
	long lCurPos = 0;

	FILE* fp = fopen("20121119_10.log", "r");

	fseek(fp, -1, SEEK_END);

	//fseek(fp, -1, SEEK_CUR);

	while( 1 )
	{
		ch = (char)fgetc(fp);
		if( ch == '\n' )
		{
			nLineCount++;

			if( nLineCount >= nLastLine )
			{
				break;
			}

			 fseek(fp, -1, SEEK_CUR);
		}

		nResult = fseek(fp, -2, SEEK_CUR);

		if( nResult != 0 )	// File 의 시작 위치 까지 왔을 때에는 break;
		{
			fseek(fp, 0, SEEK_SET);
			break;
		}
	}

	while( _fgetts(szBuf, sizeof(szBuf), fp) )
	{
		_tprintf(_T("%s\n"), szBuf);
	}

	lCurPos = ftell(fp);

	fclose(fp);

	return lCurPos;
}




Text 파일을 처음부터 읽는게 아닌 마지막에서 n 줄 부터 출력하는 예제

반응형