next up previous contents
Next: 寫入文字檔 Up: 檔案讀寫 Previous: 檔案開關   Contents   DYWANG_HOME

檔案開關實例

  1. 範例:從命令外加參數指定檔案,測試檔案是否存在。
    [dywang@dyw219 zzz]$ vim fileio1.c
    [dywang@dyw219 zzz]$ cat fileio1.c
    #include <stdio.h>
    
    int main( int argc, char *argv[] ) {
    	FILE *fp;
    	
    	fp = fopen( argv[1], "r" );
    	if( fp != NULL) {
    		printf("File %s exist.\n", argv[1]);
    	} 
    	else {
    		printf("File %s does not exist.\n", argv[1]);
    	}
    	fclose(fp);
    
    	return 0;
    }
    
  2. 編譯
    [dywang@dyw219 zzz]$ gcc -o fileio1 fileio1.c
    
  3. 執行結果:命令外加參數指定要開啟的檔案名, fileio.txt 檔案存在, fileio.aaa 不存在。
    [dywang@dyw219 zzz]$ ./fileio1 fileio.txt
    File fileio.txt exist.
    [dywang@dyw219 zzz]$ ./fileio1 fileio.aaa
    File fileio.aaa does not exist.
    



De-Yu Wang 2021-01-11