如何在文件中添加新行?

时间:2014-05-16 06:23:32

标签: c++ windows winapi file-io file-management

我正在使用Windows编程我的项目需要使用文件我尝试了以下代码

HANDLE hFile; 
char DataBuffer[255] = "This is some test data to write to the file.";
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DataBuffer[dwBytesToWrite+1]='\n';
DWORD dwBytesWritten = 0;
BOOL bErrorFlag = FALSE;



hFile = CreateFile(L"Myfile.txt",                // name of the write
                   GENERIC_WRITE,          // open for writing
                   0,                      // do not share
                   NULL,                   // default security
                   CREATE_ALWAYS,             // create new file only
                   FILE_ATTRIBUTE_NORMAL,  // normal file
                   NULL);  

使用以下代码在文件中添加两行

     bErrorFlag = WriteFile( 
                hFile,           // open file handle
                DataBuffer,      // start of data to write
                dwBytesToWrite,  // number of bytes to write
                &dwBytesWritten, // number of bytes that were written
                NULL);            // no overlapped structure
char DataBuffer1[] = "\n\nThe second line of code\n\n";
dwBytesToWrite=sizeof(DataBuffer1);

 bErrorFlag = WriteFile( 
                hFile,           // open file handle
                DataBuffer1,      // start of data to write
                dwBytesToWrite,  // number of bytes to write
                &dwBytesWritten, // number of bytes that were written
                NULL);   

该程序运行正常,但当我尝试用记事本打开“Myfile.txt”时,我得到以下结果

“这是写入文件的一些测试数据。第二行代码。”

有没有其他方法可以在文件中插入新行?

2 个答案:

答案 0 :(得分:3)

\r\n使用\n代替newline

答案 1 :(得分:1)

而不是

char DataBuffer1[] = "\n\nThe second line of code\n\n";

使用

char DataBuffer1[] = "\r\nThe second line of code\r\n";