开发者

Text and binary data in the same file

CString strFile = "c:\\test.txt";

CStdioFile aFile;

UINT nOpenFlags = CFile::modeWrite | CFile::modeCreate | CFile::typeText;

CFileException anError;

if (!aFile.Open(strFile, nOpenFlags, &anError))
{
    return false
}

int nSize = 4*sizeof(double);
double* pData = new double[2];

CString strLine, str;

// Write begin of header
strLine开发者_开发百科 = _T(">>> Begin of header <<<\n");
aFile.WriteString(strLine);

// Retrieve current position of file pointer
int lFilePos = (long) aFile.GetPosition();

// Close file
aFile.Close();

nOpenFlags = CFile::modeWrite | CFile::typeBinary;

if (!aFile.Open(strFile, nOpenFlags, &anError))
{
    return false;
}

for(int i = 0 ; i < 2 ; i++)
{
    pData[i] = i;     
}

// Set position of file pointer behind header
aFile.Seek(lFilePos, CFile::begin);

// Write complex vector
aFile.Write(pData, nSize);

// Write complex vector
aFile.Write(pData, nSize);

// Close file
aFile.Close();

Intention to create a file which contains both text data and binary data. This code is written in MFC. I wanted to similarly created a file in C# which contains both text data a and binary data. Please let me know which stream class is used to create this


Text can be written as binary data => simply use binary mode for the whole file and be done.

The only thing the text mode does is that it converts "\n" to "\r\n" on write and back on read. Since the file is partly binary and therefore not editable in regular text editor anyway, you don't need that conversion. If the file is just for your application, you just don't care and if it's for another application, just use whatever newline sequence it requires manually.


As to C#, possibly this S.O. article can give you the answer you are looking for.

The C# solution could also guide you in writing something similar for c, but I suspect you are on your own, i.e., you can use generic read/write to file. In C++, you have the possibility of doing formatted input/output from/to streams by using operator>> and operator<<.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜