创建一个文件并在其中写入内容并不是我想要的

时间:2015-03-14 13:02:10

标签: c createfile writefile

我写下面的代码:

      #include <windows.h>
      #include "stdbool.h"
      #include <winuser.h>
      #include <WinDef.h>
      #include <Winerror.h>
      #include <stdio.h>
      #include <Strsafe.h>

      #define MAX_SIZE 100


         void DisplayError(LPTSTR lpszFunction) 
         // Routine Description:
        // Retrieve and output the system error message for the   last-error code
        { 
          LPVOID lpMsgBuf;
          LPVOID lpDisplayBuf;
          DWORD dw = GetLastError(); 

         FormatMessage(
                    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                    FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS,
                    NULL,
                    dw,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    (LPTSTR) &lpMsgBuf,
                     0, 
                     NULL );

            lpDisplayBuf = 
               (LPVOID)LocalAlloc( LMEM_ZEROINIT, 
                        ( lstrlen((LPCTSTR)lpMsgBuf)
                          + lstrlen((LPCTSTR)lpszFunction)
                          + 40) // account for format string
                        * sizeof(TCHAR) );

if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, 
                 LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                 TEXT("%s failed with error code %d as follows:\n%s"), 
                 lpszFunction, 
                 dw, 
                 lpMsgBuf)))
{
    printf("FATAL ERROR: Unable to output error code.\n");
}

printf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);

LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);

   }


   int main(){
    //parameters of CreateFile()
     HANDLE hFile;  
     LPCTSTR lpFileName; 
     DWORD dwDesiredAccess; 
     DWORD dwShareMode;
     LPSECURITY_ATTRIBUTES lpSecurityAttributes;
     DWORD dwCreationDisposition; 
     DWORD dwFlagsAndAttributes; 
     HANDLE hTemplateFile; 

     //parameters of WriteFile()

     DWORD nNumberOfBytesToWrite;
     DWORD numberOfBytesWritten;
     LPOVERLAPPED lpOverlapped;
     char DataBuffer[MAX_SIZE];

     //others
     BOOL bErrorFlag; 

     //initialize args of CreateFile()
     lpFileName = "C:\\file.txt";
     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
     dwShareMode = 0;
     lpSecurityAttributes = NULL;
     dwCreationDisposition = CREATE_NEW;
     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; 
     hTemplateFile = NULL; 

     //initialize args of WriteFile()
     strcpy(DataBuffer, "This is the test file");
     nNumberOfBytesToWrite = (DWORD)strlen(DataBuffer);
     numberOfBytesWritten = 0;
     lpOverlapped = NULL;





   hFile = CreateFile(lpFileName, dwDesiredAccess, dwShareMode,
                    lpSecurityAttributes, dwCreationDisposition, 
                    dwFlagsAndAttributes, hTemplateFile);


if (hFile == INVALID_HANDLE_VALUE) 
{ 
    DisplayError(TEXT("CreateFile"));
    printf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), lpFileName);
    return;
}

printf(TEXT("Writing %d bytes to %s.\n"), nNumberOfBytesToWrite, lpFileName);

bErrorFlag = WriteFile(hFile, DataBuffer, nNumberOfBytesToWrite,
         &numberOfBytesWritten, lpOverlapped);
if (FALSE == bErrorFlag)
{
    DisplayError(TEXT("WriteFile"));
    printf("Terminal failure: Unable to write to file.\n");
}
else
{
    if (numberOfBytesWritten != nNumberOfBytesToWrite)
    {
        // This is an error because a synchronous write that results in
        // success (WriteFile returns TRUE) should write all data as
        // requested. This would not necessarily be the case for
        // asynchronous writes.
        printf("Error: dwBytesWritten != dwBytesToWrite\n");
    }
    else
    {
        printf(TEXT("Wrote %d bytes to %s successfully.\n"), numberOfBytesWritten, lpFileName);
    }
}

CloseHandle(hFile);
}

所以,正如你所看到的那样。应该为桌面创建名为file.txt的文件并在其中写入一些文本的程序。 我使用Microsoft Visual C ++ Express,它编译时没有错误。但是当我通过单击绿色播放按钮运行它时,我看到我的桌面上没有创建这样的文件。

通过搜索我可能出现的错误,我还在https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx上读到他们使用的代码几乎相同。除了我不包括显示错误部分。

所以,我的问题:它可能是什么原因不起作用? 我(程序)需要一些额外的权限来做到这一点吗? 例如,我在Ubuntu中使用open()和amp; write(),除了我使用&#34; /tmp/file.txt"作为destionation目录。它没有额外的权限。

最好的问候,

2 个答案:

答案 0 :(得分:1)

这是写文件名的错误方法

"C:\Desktop\file.txt";

你需要逃避'\'\f实际上是转义序列

"C:\\Desktop\\file.txt";

而且,显然不会在桌面上创建文件,而是尝试使用

"C:\\file.txt";

并检查您的C:驱动器以查看该文件。

答案 1 :(得分:1)

代码使用了错误的桌面目录路径。

对于Windows 7(以及大多数版本的Windows),路径为:

确保在每个目录级别使用两个反斜杠

C:\用户\ yourUsername \桌面