C语言打开一个文件的数据到另一个文件里,为什么总显示cannot open file

Python070

C语言打开一个文件的数据到另一个文件里,为什么总显示cannot open file,第1张

第一,确保这两个文件存在第二,改成绝对路径试一下,也就是带盘符那种,比如D:\\xxx\\xxx这样的,应该可以然后就是试验该放在哪里了,根据你ide不同,有可能是源文件所在路径,不过看起来不是还可能是编译出来的exe所在路径,或者是工程文件所在路径都试一下其实用绝对路径是个不错的选择

CreateFile可以打开和创建文件,会返回句柄Handle。

然后用WriteFile和ReadFile来操作,最后需要CloseHandle.

#include <windows.h>

#include <stdio.h>

#define BUFSIZE 4096

int main()

{

HANDLE hFile

HANDLE hTempFile

DWORD dwBytesRead, dwBytesWritten, dwBufSize=BUFSIZE

char szTempName[MAX_PATH]

char buffer[BUFSIZE]

char lpPathBuffer[BUFSIZE]

// Open the existing file.

hFile = CreateFile("original.txt", // file name

GENERIC_READ, // open for reading

0, // do not share

NULL, // default security

OPEN_EXISTING, // existing file only

FILE_ATTRIBUTE_NORMAL, // normal file

NULL) // no template

if (hFile == INVALID_HANDLE_VALUE)

{

printf("Could not open file.")

return 0

}

// Get the temp path

GetTempPath(dwBufSize, // length of the buffer

lpPathBuffer) // buffer for path

// Create a temporary file.

GetTempFileName(lpPathBuffer, // directory for temp files

"NEW",// temp file name prefix

0,// create unique name

szTempName) // buffer for name

hTempFile = CreateFile((LPTSTR) szTempName, // file name

GENERIC_READ | GENERIC_WRITE, // open for read/write

0,// do not share

NULL, // default security

CREATE_ALWAYS,// overwrite existing file

FILE_ATTRIBUTE_NORMAL,// normal file

NULL) // no template

if (hTempFile == INVALID_HANDLE_VALUE)

{

printf("Could not create temporary file.")

return 0

}

// Read 4K blocks to the buffer.

// Change all characters in the buffer to upper case.

// Write the buffer to the temporary file.

do

{

if (ReadFile(hFile, buffer, 4096,

&dwBytesRead, NULL))

{

CharUpperBuff(buffer, dwBytesRead)

WriteFile(hTempFile, buffer, dwBytesRead,

&dwBytesWritten, NULL)

}

} while (dwBytesRead == BUFSIZE)

// Close both files.

CloseHandle(hFile)

CloseHandle(hTempFile)

// Move the temporary file to the new text file.

if (!MoveFileEx(szTempName,

"allcaps.txt",

MOVEFILE_REPLACE_EXISTING))

{

printf("Could not move temp file.")

return 0

}

}