在文件中写入新的行字符

Writing new line character in file

本文关键字:字符 文件      更新时间:2023-10-16

我只想在文件中写入空白行。我使用以下代码,但不工作。

        char* RegID;
        RegID = "10";
        char* mndtime;
        mndtime  = "10";
        char* resourcetype;
        resourcetype  = "Backup";
        char* ressubtype;
        ressubtype = "shadowprotect";
        char* DataBuffer = new char[100];
        StrCpy(DataBuffer,"<wpshadowprotectstatus>");
        strcat(DataBuffer,"n");
        strcat(DataBuffer,"<mndtime>");
        strcat(DataBuffer,RegID);
        strcat(DataBuffer,"<\mndtime>n");
        strcat(DataBuffer,"<resourcetype>");
        strcat(DataBuffer,RegID);
        strcat(DataBuffer,"<\resourcetype>n");
        strcat(DataBuffer,"<ressubtype>");
        strcat(DataBuffer,RegID);
        strcat(DataBuffer,"<\ressubtype>n");
        strcat(DataBuffer,"<jobname>");
        strcat(DataBuffer,RegID);
        strcat(DataBuffer,"<\jobname>n");
        strcat(DataBuffer,"<jobstarttime>");
        strcat(DataBuffer,RegID);
        strcat(DataBuffer,"<\jobstarttime>n");
        HANDLE hFile; 
        hFile = CreateFile("text.txt",                // name of the write
                           GENERIC_WRITE,          // open for writing
                           0,                      // do not share
                           NULL,                   // default security
                           CREATE_NEW,             // create new file only
                           FILE_ATTRIBUTE_NORMAL,  // normal file
                           NULL);                  // no attr. template
        if (hFile == INVALID_HANDLE_VALUE) 
        { 
            return 0;
        }
        DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
        DWORD dwBytesWritten = 0;
        BOOL bErrorFlag = FALSE;
        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

但是我不知道为什么新的行不转储在文本文件

注意:-1)我不想使用std:: library c++。2)不想使用xml解析器

在Windows上使用rn作为换行符

您的XML格式是错误的。XML结束标记使用/字符,而不是字符。并且您正在为所有XML值编写相同的RegID变量,而不是使用其他变量(mndtime, resourcetype等)。

Windows?如果是,将n替换为rn。对于FILE*/iostream,它会在运行时自动完成,但对于WriteFile则不会。当然,你需要两个行尾来得到空行。

顺便说一句,用strcat生成长字符串的复杂度是0 (N^2),这是非常糟糕的。