【发布时间】: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