Cum citesc un fisier text linie cu linie?
Rezolvare:Simplu. Instantiez un obiect tip CStdioFile si apelez CStdioFile::ReadString pana citesc toate liniile (pana cand ReadString intoarce FALSE).
Exemplu:
Cod: |
void CFoo::ReadTextFile(LPCTSTR pszFileName, CStringArray& arrLines) { arrLines.RemoveAll(); CString strLine; TRY { CStdioFile file(pszFileName, CFile::modeRead); while(file.ReadString(strLine)) { arrLines.Add(strLine); } } CATCH_ALL(e) { e->ReportError(); // shows what's going wrong } END_CATCH_ALL } |
Cum citesc intreg continutul unui fisier (text) intr-un obiect de tip CString?
Rezolvare:Instanitiez un obiect de tip CFile, ii aflu lungimea cu CFile::GetLength apoi apelez functia CFile::Read.
Exemplu:
Cod: |
void CFoo::ReadTextFile(LPCTSTR pszFileName, CString& strText) { strText.Empty(); TRY { CFile file(pszFileName, CFile::modeRead); const DWORD dwLength = file.GetLength(); file.Read(strText.GetBuffer(dwLength), dwLength); strText.ReleaseBuffer(); } CATCH_ALL(e) { e->ReportError(); } END_CATCH_ALL } |