64,649
社区成员
发帖
与我相关
我的任务
分享
#include <Windows.h>
#include <stdio.h>
#define BUFSIZE 512
int main()
{
HANDLE hFile;
HANDLE hTempFile;
DWORD dwRetVal;
DWORD dwBytesRead;
DWORD dwBytesWritten;
DWORD dwBufSize=BUFSIZE;
UINT uRetVal;
char szTempName[BUFSIZE];
char buffer[BUFSIZE];
char lpPathBuffer[BUFSIZE];
BOOL fSuccess;
// 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 ("CreateFile failed with error %d.\n",
GetLastError());
return (1);
}
// Get the temp path.
dwRetVal = GetTempPath(dwBufSize, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > dwBufSize || (dwRetVal == 0))
{
printf ("GetTempPath failed with error %d.\n",
GetLastError());
return (2);
}
// Create a temporary file.
uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
"NEW", // temp file name prefix
0, // create unique name
szTempName); // buffer for name
if (uRetVal == 0)
{
printf ("GetTempFileName failed with error %d.\n",
GetLastError());
return (3);
}
// Create the new file to write the upper-case version to.
hTempFile = CreateFile((LPTSTR) szTempName, // file name
GENERIC_READ | GENERIC_WRITE, // open r-w
0, // do not share
NULL, // default security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL,// normal file
NULL); // no template
if (hTempFile == INVALID_HANDLE_VALUE)
{
printf ("CreateFile failed with error %d.\n",
GetLastError());
return (4);
}
// Read BUFSIZE 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,
BUFSIZE,
&dwBytesRead,
NULL))
{
CharUpperBuff(buffer, dwBytesRead);
fSuccess = WriteFile(hTempFile,
buffer,
dwBytesRead,
&dwBytesWritten,
NULL);
if (!fSuccess)
{
printf ("WriteFile failed with error %d.\n",
GetLastError());
return (5);
}
}
else
{
printf ("ReadFile failed with error %d.\n",
GetLastError());
return (6);
}
} while (dwBytesRead == BUFSIZE);
// Close the handles to the files.
fSuccess = CloseHandle (hFile);
if (!fSuccess)
{
printf ("CloseHandle failed with error %d.\n",
GetLastError());
return (7);
}
fSuccess = CloseHandle (hTempFile);
if (!fSuccess)
{
printf ("CloseHandle failed with error %d.\n",
GetLastError());
return (8);
}
// Move the temporary file to the new text file.
fSuccess = MoveFileEx(szTempName,
"allcaps.txt",
MOVEFILE_REPLACE_EXISTING);
if (!fSuccess)
{
printf ("MoveFileEx failed with error %d.\n", GetLastError());
return (9);
}
return (0);
}