1 #include<iostream> 2 #include<stdio.h> 3 #include<string.h> 4 using namespace std; 5 6 int main() 7 { 8 9 10 //C语言的文件操作 11 /* 12 13 FILE *指针变量标识符 14 15 //fopen fclose 16 17 18 //fgetc fputc //by Character 字符读写 19 //fgets fputs //by stream 字符串读写 20 //fread fwrite //by block 数据块读写 21 //fscanf fprintf //格式化读写 22 23 fscanf(文件指针,格式字符串,输入表列); 24 fscanf(fp,"%d%s",&i,s); 25 fprintf(fp,"%d%c",j,ch); 26 27 //fseek ftell 28 //rewind 29 30 在移动位置指针之后,即可用前面介绍的任一种读写函数进行读写。由于一般是读写一 31 个数据据块,因此常用fread 和fwrite 函数。(比如一次读一个结构体,或者写入一个结构体) 32 33 34 //feof(文件指针) 35 //ferror(文件指针) 36 //clearerr(文件指针) 37 38 */ 39 40 // 使用fseek 定位文件指针的位置 41 // int fseek( FILE *stream, long offset, int origin ); 42 /* 43 //fseek(文件指针,位移量,起始点) 44 stream 45 46 Pointer to FILE structure 47 48 offset 49 50 Number of bytes from origin 51 52 origin 53 54 Initial position 55 56 SEEK_SET 0 57 58 Beginning of file 59 60 SEEK_CUR 1 61 62 Current position of file pointer 63 64 SEEK_END 2 65 66 End of file 67 68 */ 69 70 /* 71 fread(buffer,size,count,fp); 72 fwrite(buffer,size,count,fp); 73 74 75 buffer 是一个指针,在fread 函数中,它表示存放输入数据的首地址。 76 在fwrite 函数中,它表示存放输出数据的首地址。 77 size 表示数据块的字节数。 78 count 表示要读写的数据块块数。 79 fp 表示文件指针。 80 81 82 83 fread(fa,4,5,fp); 84 其意义是从fp 所指的文件中,每次读4 个字节(一个实数)送入实数组fa 中,连续读5 次, 85 即读5 个实数到fa 中。 86 87 */ 88 89 90 91 FILE* fp = NULL; 92 93 char *szName = "G:\1.txt"; 94 fp = fopen(szName,"w"); 95 96 char *szTemp = "Do your Best!"; 97 98 fseek(fp,0,2);//SEEK_END; 99 100 int nFileLen = ftell(fp); 101 102 int len = strlen(szTemp); 103 cout<<nFileLen<<endl; 104 cout<<szTemp<<endl; 105 106 107 // rewind(fp); 108 fseek(fp,0,SEEK_SET); 109 fwrite(szTemp,len,1,fp); 110 111 fclose(fp); 112 return 0; 113 }