C/C++基础 (file)

C:\Users\LAILAI\Desktop>g++ --version
g++.exe (GCC) 4.7.0 20111220 (experimental)
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\Users\LAILAI\Desktop>g++ filename.cpp
// filename.cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {

	const char* filename = "c:\\cfiletestD.txt"; // "c:/cfiletest.txt";
	FILE* fp = fopen(filename, "wb");
	if (fp == NULL) {

		printf("failed to open file");
		return -1;
	}
	int buf[4] = { 0xA001,0xB002,0xC003,0xD004 }; // 40961,45058,49155,53252,
	for (int i = 0; i < 4; i++) {
		char text[16];
		sprintf(text, "%d,", buf[i]);
		fwrite(text, 1, strlen(text), fp);
	}
	printf("Successto open file: c:/cfiletest.txt\n");
	system( "PAUSE ");
	return 0;
}
// filename.cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {

	const char* filename = "c:\\cfiletestA.txt"; // "c:/cfiletestA.txt";
	FILE* fp = fopen(filename, "wb");
	if (fp == NULL) {

		printf("failed to open file");
		return -1;
	}
	int buf[4] = { 0xA001,0xB002,0xC003,0xD004 };
	for (int i = 0; i < 4; i++) {
		char text[16];
		sprintf(text, "%d,", buf[i]);
		fwrite(text, 1, strlen(text), fp);  // 40961,45058,49155,53252,
	}
	printf("Successto open file: c:/cfiletest.txt\n");
	system( "PAUSE ");
	return 0;
}
#include<stdio.h>
#include<string.h>

int main() {
	const char* filename = "c:\\cfiletestB.txt"; // "c:/cfiletestB.txt";
	FILE* fp = fopen(filename,"wb");
	if (fp == NULL) {
	
		printf("failed to open file");
		return -1;
	
	}
	char buf[] = "hello!";
	fwrite(buf,1,6,fp);
	int a = 12345;
	char text[16];
	sprintf(text, "%d", a);
	fwrite(text, 1, strlen(text), fp); // hello!12345
	fclose(fp);
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
	const char* filename = "c:\\cfiletestB.txt"; // "c:/cfiletestB.txt";
	FILE* fp = fopen(filename, "rb");
	if (fp == NULL) {
		printf("failed to open file");
		return -1;
	}
	char buf[128];
	//int n = fread(buf, 1, 128, fp);
	while (! feof (fp)) {  //streams 
		int n = fread(buf,1,4,fp);
		if (n > 0) {
			printf("read %d bytes\n", n);
		}	
	}
	fclose(fp);
	system( "PAUSE ");
	return 0;
}
#include<stdio.h>
#include<string.h>

int main() {
	const char* filename = "c:\\cfiletestA.txt"; // "c:/cfiletestA.txt";
	FILE* fp = fopen(filename, "rb");
	if (fp == NULL) {
		printf("failed to open file");
		return -1;
	}
	unsigned char buf[16];
	int ret = fseek(fp,6,SEEK_SET);  // feof (fp) + 6
	int n = fread(buf,1,5,fp);
	buf[5] = 0;
	printf("%s\n",buf); // 45058
	
	fclose(fp);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值