茴字的N种写法 (读《把脉VC++》笔记)

在Windows编程中有许多方法实现文件写入和读取,下面是《把脉VC++》中介绍的几种。

 

1、使用Windows API

Windows API提供了CreateFile, WriteFile, ReadFile函数可以实现文件的打开,写入和读取。

 

CreateFile函数原型:

HANDLE CreateFile( LPCTSTR lpFileName, // 指向文件名的指针 DWORD dwDesiredAccess, // 访问模式 DWORD dwShareMode, // 共享模式 LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 指向安全属性的指针 DWORD dwCreationDisposition, // 如何创建 DWORD dwFlagsAndAttributes, // 文件属性 HANDLE hTemplateFile // 用于复制文件句柄 );

 

WriteFile函数原型:

BOOL WriteFile( HANDLE hFile, // 文件句柄 LPCVOID lpBuffer, // 写入文件的Buffer DWORD nNumberOfBytesToWrite, // Buffer的大小 LPDWORD lpNumberOfBytesWritten, // 接收写入的字节数 LPOVERLAPPED lpOverlapped // 指向OVERLAPPED结构的指针 );

 

ReadFile函数原型:

BOOL ReadFile( HANDLE hFile, // 文件句柄 LPVOID lpBuffer, // 读取文件后存放的Buffer DWORD nNumberOfBytesToRead, // Buffer的大小 LPDWORD lpNumberOfBytesRead, // 接收读取的字节数 LPOVERLAPPED lpOverlapped // 指向OVERLAPPED结构的指针 );

 

 

 

实现代码如下:

 

#include "stdafx.h" #include <Windows.h> #include <cstdio> int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile; DWORD nBytes; hFile = CreateFile(_T("test.out"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); char msg[] = "茴香豆的茴"; if(hFile != INVALID_HANDLE_VALUE) { WriteFile(hFile, &msg, sizeof(msg), &nBytes, NULL); CloseHandle(hFile); } hFile = CreateFile(_T("test.out"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL); if (hFile != INVALID_HANDLE_VALUE) { char line[256] = {0}; BOOL bResult; bResult = ReadFile(hFile, &line, sizeof(line), &nBytes, NULL); if (nBytes != 0) { printf("%s/r/n", line); } CloseHandle(hFile); } return 0; }

 

2、使用标准C++库

在标准C++中使用流(stream)来操作文件,流操作文件是在内存中进行的,所以流缓冲区是内存,ofstream是从内存到硬盘的操作,ifstream是从硬盘到内存的操作。

 

示例代码如下:

#include "stdafx.h" #include <iostream> #include <fstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ofstream out("test.out"); out << "茴香豆的茴"; out.close(); ifstream in("test.out"); char line[255]; in.getline(line, 255); cout << line << endl; return 0; }

 

 

 3、使用C Runtime Library

在C运行时库中给出了操作文件的函数,fopen用于创建和打开文件;fclose用于关闭打开的文件;fscanf从文件中读取文本;fprintf向文件输出文本。

 

示例代码如下:

#include "stdafx.h" #include <cstdio> int _tmain(int argc, _TCHAR* argv[]) { FILE* fp = fopen("test.out", "w"); fprintf(fp, "茴香豆的茴"); fclose(fp); fp = fopen("test.out", "r"); char line[255]; fscanf(fp, "%s", line); printf("%s/r/n", line); fclose(fp); return 0; }

 

 

4、使用C++/CLI实现

微软的C++/CLI是基于.NET Framework的实现的,即托管代码(Managed Code)。

 

示例代码如下:

#include "stdafx.h" using namespace System; using namespace System::IO; int main(array<System::String ^> ^args) { String^ path = "test.out"; StreamWriter^ sw = File::CreateText(path); sw->WriteLine("茴香豆的茴"); sw->Close(); StreamReader^ sr = File::OpenText(path); String^ s = ""; if (s = sr->ReadLine()) { Console::WriteLine(s); } return 0; }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(File,null,buffer,vc++,FP,attributes)