Click here to Skip to main content
15,038,642 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When outputting using a struct
Is there a way to line up when outputting to a text file?

like this (Text.txt)
item1          item2         item3          item4          item5
dataab         datadd        dat            dataabceed     data         
data123432     dataabcdefgad data___NULLL   data           data12341


C++
// struct use pack
#pragma pack(push, 2)
struct stReportItem
{
	TCHAR psz_REPORT_ITEMS[REPORT_ITEM_CNT][STRLEN];
	stReportItem()
	{
		for(int i = 0; i < REPORT_ITEM_CNT; i++)
			memset(psz_REPORT_ITEMS[i], '0', sizeof(TCHAR) * STRLEN);

	}
};
#pragma pack(pop)


What I have tried:

C++
void CMainDlg::OnBnClickedBtnOutTxt()
{
	CFile file;

	if (!file.Open(_T("C:\\Temp\\Text.txt"), CFile::modeCreate | CFile::modeWrite, NULL))
	{
		AfxMessageBox(_T("Failed create file"));
		return;
	}

	for (int i = 0; i < m_vstReport.size(); i++)
	{
		stReportItem stTemp = m_vstReport.at(i);
		for (int j = 0; j < REPORT_ITEM_CNT; j++)
		{
			file.Write(stTemp.psz_REPORT_ITEMS[j], sizeof(stTemp.psz_REPORT_ITEMS[j]));
		}
		file.Write(_T("\r\n"), sizeof(_T("\r\n")));
	}

	file.Flush();
	file.Close();

	ShellExecute(NULL, "open", "c:\\windows\\notepad.exe", _T("C:\\Temp\\Text.txt"), NULL, SW_SHOWNORMAL);
}
Posted
Updated 18-Jun-21 0:42am
v2

Use sprintf (printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s - cppreference.com[^]) to format the text into fixed field widths. You can then write the resultant string to your CFile object.
   
v2
Comments
Maciej Los 18-Jun-21 3:45am
   
5ed!
I haven't seen the question till i did changes (formatting).
Richard MacCutchan 18-Jun-21 6:59am
   
Thanks. I modified my answer to allow the use of file.Write.
The common way is to write string conversion function for struct. Like

C++
// create string with delimiter (like ',') for all data
CString toText(stReportItem *data);
// parse the above data into members of struct
stReportItem.parse(CString text);
by the way
C++
memset(psz_REPORT_ITEMS[i], 0, sizeof(struct stReportItem));
zero out string and not writing a char in the buffer
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900