C/C++/WIN32 三种方式实现读写文件

/************C**************/

#include "stdafx.h"
#include <Windows.h>
#include<iostream>
#include <fstream>
#define MAX_LINE 1024   //定义txt中最大行数。可调整更改
using namespace std;
int main()
{
char buf[MAX_LINE] = {}; /*缓冲区*/
FILE *fp,*fw;           /*文件指针*/
fopen_s(&fp,"test.txt", "r");
fopen_s(&fw,"a.txt", "r+");//r+可以选择位置,a只能在最后加入内容,w会清空原来内容
if (fp == NULL)
{
perror("fail to read");
system("pause");
return -1;
}
fseek(fw, -100, SEEK_END);   //从哪个位置读取  字节偏移量SET,CUR,END
while (fgets(buf, MAX_LINE, fp) != NULL)
{
fputs(buf, fw);
int len = strlen(buf); /*行字符个数*/
buf[len - 1] = '\0';   /*去掉换行符,字符串结束符*/
   printf("%s  \n", buf);
  
}
fclose(fp);
fclose(fw);
system("pause");
return 0;

}

/*****************C++**************/

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string temp;
ifstream input;
input.open("test.txt", ios::in);//打开输入文件
cout << "inpos=" << input.tellg() << endl;
ofstream output;
output.open("aa.txt", ios::out | ios::app);//app每次写入前找到流结尾,out 为写打开
output.seekp(-20, ios::end); //beg让文件指针定位到离文件开头10个字节的位置,end结束,cur当前位置
cout << "outpos=" << output.tellp() << endl;
while (getline(input, temp))
{
output << temp;
output << endl;
}
system("pause");
return 0;

}

/************WIN32************/

#include "stdafx.h"
#include <windows.h>
#include<iostream>
using namespace std;
int _tmain(int argc,_TCHAR *argv)
{
TCHAR szFile[] = _T("test.txt");
HANDLE hFile = CreateFile(szFile, //创建文件的名称。
GENERIC_READ,        // GENERIC_WRITE | GENERIC_READ, 写和读文件。 
FILE_SHARE_READ,     // 共享读。
NULL,             // 缺省安全属性
OPEN_EXISTING,    // CREATE_ALWAYS  覆盖文件(不存在则创建)    OPEN_EXISTING 打开文件(不存在则报错)
FILE_ATTRIBUTE_NORMAL,  // 一般的文件。
NULL);    // 模板文件为空。
if (hFile == INVALID_HANDLE_VALUE)  //无效值
{
OutputDebugString(TEXT("CreateFile fail!\r\n"));

}

DWORD dwSize = GetFileSize(hFile, NULL); //读取文件大小
cout << "dwSize=" << dwSize << endl;
char* cBuf = new char[dwSize];          //在堆上开辟缓冲区,等待读入文件数据

    RtlZeroMemory(cBuf, sizeof(char)*(dwSize));       //用0填充缓冲区
SetFilePointer(hFile, 10, NULL, FILE_BEGIN);
DWORD haveReadByte;
ReadFile(hFile, cBuf, dwSize, &haveReadByte, 0);
//读入数据到缓冲区 
TCHAR writeFile[] = _T("a.txt");
HANDLE wFile = CreateFile(writeFile, //创建文件的名称。
GENERIC_WRITE,        // GENERIC_WRITE | GENERIC_READ, 写和读文件。 
0,     // 不共享。
NULL,             // 缺省安全属性
OPEN_ALWAYS,    // CREATE_ALWAYS  覆盖文件(不存在则创建)    OPEN_EXISTING 打开文件(不存在则报错)
FILE_ATTRIBUTE_NORMAL,  // 一般的文件。
NULL);    // 模板文件为空。
GetLastError();
DWORD dwreturnsize;
WriteFile(wFile, cBuf, dwSize, &dwreturnsize, NULL);
cout << "dwreturnsize=" << dwreturnsize << endl;
delete[] cBuf;
CloseHandle(hFile);
CloseHandle(wFile);//关闭文件
system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值