1. 程式人生 > >C/C++基礎 (file)

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;
}