C/C++读写文件示例

目录

C语言写文件

/*
	C语言写文件 
	"r":只能从文件中读数据,该文件必须先存在,否则打开失败
	"w":只能向文件写数据,若指定的文件不存在则创建它,如果存在则先删除它再重建一个新文件
	"a":向文件增加新数据(不删除原有数据),若文件不存在则打开失败,打开时位置指针移到文件末尾
	"r+":可读/写数据,该文件必须先存在,否则打开失败
	"w+":可读/写数据,用该模式打开新建一个文件,先向该文件写数据,然后可读取该文件中的数据
	"a+":可读/写数据,原来的文件不被删去,位置指针移到文件末尾
*/
#include<stdio.h>
#include<stdlib.h>

int main() {
    
    
		FILE* pf = fopen("test.txt", "w");
		if (pf == NULL) {
    
    
			printf("fail to open file!");
			exit(-1);
		}
		fputs("abcd", pf);
		fputs("efghi\n", pf);
		fputs("jklmn\n", pf);
		//关闭文件
		fclose(pf);
		pf = NULL;
		return 0;
}

C语言读文件

/*
	C语言读文件 
	"r":只能从文件中读数据,该文件必须先存在,否则打开失败
	"w":只能向文件写数据,若指定的文件不存在则创建它,如果存在则先删除它再重建一个新文件
	"a":向文件增加新数据(不删除原有数据),若文件不存在则打开失败,打开时位置指针移到文件末尾
	"r+":可读/写数据,该文件必须先存在,否则打开失败
	"w+":可读/写数据,用该模式打开新建一个文件,先向该文件写数据,然后可读取该文件中的数据
	"a+":可读/写数据,原来的文件不被删去,位置指针移到文件末尾
*/
#include<stdio.h>
#include<stdlib.h>

int main() {
    
    
	char line[500];
	FILE *fp;
	if ((fp=fopen("test.txt", "r")) == NULL) {
    
    
		printf("file fail to open!\n");
		exit(-1);
	}
	while (fgets(line, sizeof(line), fp) != NULL) {
    
    
		printf("%s", line);
	} 
	fclose(fp);
	fp = NULL;
	return 0;
}

C++读文件

/*
	C++读文件 
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std; 

int main () {
    
    
    char buffer[256];
    fstream in("test.txt", ios::in);
    if (! in.is_open()) {
    
    
    	cout << "Error opening file"; exit (1);	
	}
    while (!in.eof() ) {
    
    
        in.getline (buffer,100);
        cout << buffer << endl;
    }
    in.close();
    return 0;
}

C++写文件

/*
	C++写文件 
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std; 

int main () {
    
    
    char buffer[256];
	fstream out("out.txt", ios::out || ios::app);
    if (out.is_open())  {
    
    
        out << "This is a line.\n";
        out << "This is another line.\n";
	}
    out.close();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gls_nuaa/article/details/130196908