C++ 如何向文件中添加新行?

C++ 如何向文件中添加新行?,c++,windows,winapi,file-io,file-management,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 = FA

我正在使用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”时,我得到以下结果

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


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

使用
\r\n
而不是
\n
用于
新行
使用
\r\n
而不是
\n
用于
新行
而不是

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

而不是

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


DataBuffer[dwBytesToWrite+1]='\n'不添加+1,因为
长度将始终比上一个索引为+1。
DataBuffer[dwBytesToWrite+1]='\n'不添加+1,因为
length
总是比上一个索引+1。C库不是自动将
\n
转换为eol序列吗?自我回答我的评论:
WriteFile
不是来自C库。C库不是自动将
\n
转换为eol序列吗?自我回答我的评论:
WriteFile
不是来自C库。