将字输入到某个文件中

以各种方式将茴字输入到某个文件

window API:

// c++_a.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>




using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

	HANDLE hFile;
	DWORD nBytes;

	//写入文件
	hFile = CreateFile(_T("test.txt"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL,CREATE_ALWAYS,0,NULL);
	char msg[] = "茴香豆的茴";
	if ( hFile != INVALID_HANDLE_VALUE)
	{
		WriteFile(hFile, msg, sizeof(msg) - 1, &nBytes, NULL);
		CloseHandle(hFile);
	}

	//
	hFile = CreateFile(_T("test.txt"), 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)
		{
		    cout<<line<<endl;
		}
		CloseHandle(hFile);
	}
	system("pause");

	return 0;
}

c++标准库

// c++_a.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	//写入文件
	ofstream out("test.txt");
	out << "茴香豆的茴hui";
	out.close();

	//读取文件
	ifstream in("test.txt");
	char line[256];
	in.getline(line, 256);
	cout<<line<<endl;


	system("pause");

	return 0;
}

CRT:

// c++_a.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <cstdio>

int _tmain(int argc, _TCHAR* argv[])
{
	//写入文件
	FILE * fp;
	fopen_s(&fp, "test.txt", "w");
	fprintf_s(fp, "茴香的茴");
	fclose(fp);

	//读取文件
	fopen_s(&fp, "test.txt", "r");
	char line[256];
	fscanf_s(fp, "%s", line, 256);
	printf_s("%s\r\n", line);
	fclose(fp);

	system("pause");

	return 0;
}

MFC封装了CFile类

// c++_b.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "c++_b.h"
#include <stdlib.h>
#include <afx.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

int _tmain(int argc, _TCHAR* argv[])
{
	//写入文件
	CFile file;
	if (file.Open(_T("test.txt"), CFile::modeCreate | CFile::modeWrite))
	{
		char line[256] = "茴香豆的茴";
		file.Write(line, sizeof(line));
		file.Close();
	}

	//读取文件
	if (file.Open(_T("test.txt"), CFile::modeRead))
	{
		char line[256];
		if (file.Read(line, 256) != 0)
		{
			printf("%s\r\n", line);
		}
		file.Close();
	}

	system("pause");

	return 0;
}

c++/cli输出:

// c++_d.cpp: 主项目文件。

#include "stdafx.h"


using namespace System;
using namespace System::IO;

int main(array<System::String ^> ^args)
{
    String^ path = "test.txt";

	//写文件
	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;
}


你可能感兴趣的:(将字输入到某个文件中)