【问题标题】:How can I add new line to the file? [duplicate]如何在文件中添加新行? [复制]
【发布时间】:2014-05-16 06:23:32
【问题描述】:

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

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

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

【问题讨论】:

  • DataBuffer[dwBytesToWrite+1]='\n'; 不要加 +1,因为length 总是比上一个索引 +1。

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


【解决方案1】:

使用\r\n 代替\n 代替newline。

【讨论】:

  • C库不是自动将\n翻译成eol序列吗?
  • 自我回答我的评论:WriteFile 不是来自 C 库。
【解决方案2】:

而不是

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

使用

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

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2016-07-22
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多