1. 程式人生 > >代碼行最大長度宜控制在 70 至 80 個字符以內

代碼行最大長度宜控制在 70 至 80 個字符以內

get 指針 out dat文件 con long could not 文件頭 std

代碼行最大長度宜控制在 70 至 80 個字符以內。代碼行不要過長,否 則眼睛看不過來,也不便於打印。

 1 #include <iostream>
 2 #include <process.h>
 3 #include<stdio.h>
 4 #include<conio.h>
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 using namespace std;
 7 int main(int
argc, char** argv) { 8 9 //聲明變量 10 int i; 11 char ch; 12 FILE *fp1; 13 14 //以寫入方式打開d.dat文件 15 if ((fp1=fopen("d.dat","w"))==NULL) { 16 cout<<"\nCould not open the file."<<endl; 17 cout<<"Exiting program."<<endl; 18 exit(1
); //結束程序執行 19 } 20 21 //循環從鍵盤上讀取字符,寫入文件 22 cout<<"char:"; 23 cin>>ch; 24 while (ch!=*) { 25 fputc(ch,fp1); //將字符寫到fp1指向的"流"文件中 26 cin>>ch; 27 } 28 cout<<"--------------------"<<endl; 29 fclose(fp1); //關閉文件 30 31 //以讀方式打開d.dat文件
32 if ((fp1=fopen("d.dat","r"))==NULL) 33 { 34 cout<<"\nCould not open the file."<<endl; 35 cout<<"Exiting program."<<endl; 36 exit(1); //結束程序執行 37 } 38 39 //循環從文件讀取字符,並顯示 40 while ((ch=fgetc(fp1))!=EOF) 41 cout<<ch; 42 cout<<endl<<"--------------------"<<endl; 43 44 //以下按倒序方式讀取文件中的字符,並顯示 45 for (i=-1;;i--) { 46 fseek(fp1,i,2); //設置文件指針,偏移量為i,相對文件尾 47 if ((ch=fgetc(fp1))!=EOF) 48 cout<<ch; 49 else 50 break; 51 } 52 cout<<endl<<"--------------------"<<endl; 53 54 //以下讀取"流"文件中偶數位置上的字符,並打印 55 long position; 56 for (i=0;;i=i+2) { 57 fseek(fp1,i,0); //設置文件指針,偏移量為i,相對文件頭 58 position=ftell(fp1); 59 if ((ch=fgetc(fp1))==EOF) //遇到文件尾,則退出,否則打印讀取的字符 60 break; 61 else { 62 cout<<position<<" :"<<ch<<endl; 63 } 64 } 65 cout<<endl; 66 67 fclose(fp1); //關閉文件 68 return 0; 69 }

代碼行最大長度宜控制在 70 至 80 個字符以內