c语言程序设计文件操作方法示例(CreateFile和fopen)
实例:
(1)第一种方法CreateFile
#include "stdafx.h"
#include <windows.h>
void main(int argc, char* argv[])
{
HANDLE hDevice = CreateFile("C://S.txt",
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
printf("Failed to obtain file with %d error code !/n",GetLastError());
return;
}
DWORD dwSize = GetFileSize(hDevice,NULL);
printf("%d /n",dwSize);
char chBuffer[10] = "5469";
DWORD dwWriteSize = 0;
BOOL bRet = WriteFile(hDevice,chBuffer,4,&dwWriteSize,NULL);
if(bRet)
{
printf("write file success /n");
}
FlushFileBuffers(hDevice); //将缓冲区数据写入磁盘
LONG IDistance = 0;
DWORD dwPtr = SetFilePointer(hDevice,IDistance,NULL,FILE_BEGIN); //调整文件指针到文件开头
DWORD dwReadSize = 0;
bRet = ReadFile(hDevice,chBuffer,10,&dwReadSize,NULL);
if (bRet)
{
printf("chbuffer is %s /n",chBuffer);
}
CloseHandle(hDevice);
return ;
}
(2)第二种方法流文件操作FILE
char datain[101];
FILE *fp_sys;
fp_sys = fopen("要打开的文件名", "rb"); //第二个参数为打开方法,r代表读,b代表二进制方式
if(fp_sys == NULL) {
AfxMessageBox("无法打开充值卡文件");
上一篇:C++中delete和delete[]的区别详细介绍
栏 目:C代码
下一篇:C++利用链栈实现表达式求值
本文标题:c语言程序设计文件操作方法示例(CreateFile和fopen)
本文地址:http://www.codeinn.net/misctech/64510.html