1 / 9

情報処理演習 C2 ファイル 操作に ついて (2)

情報処理演習 C2 ファイル 操作に ついて (2). ファイル操作 (1). temp .txt. FILE* fp = fopen (&quot; temp.txt&quot;,&quot;r &quot;); int value0; fscanf ( fp ,&quot;%d<br>&quot;,&amp;value0); int values[4]; fscanf ( fp ,&quot;%d, %d, %d, %d n&quot;,&amp;values [0],&amp;values[1],&amp;values[2],&amp;values[3]); char buf0[1024]; fgets (buf0,sizeof(buf0), fp );

bina
Download Presentation

情報処理演習 C2 ファイル 操作に ついて (2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 情報処理演習C2ファイル操作について (2)

  2. ファイル操作 (1) temp.txt FILE* fp = fopen("temp.txt","r"); int value0; fscanf(fp,"%d\n",&value0); int values[4]; fscanf(fp,"%d, %d, %d, %d\n",&values[0],&values[1],&values[2],&values[3]); char buf0[1024]; fgets(buf0,sizeof(buf0),fp); char buf1[1024]; fgets(buf1,sizeof(buf1),fp); fclose(fp); 1 2, 3, 4, 5 L 3 L 4 value0 values[4] buf0[1024] buf1[1024]

  3. ファイル操作 (2) temp.txt FILE* fp = fopen("temp.txt","r"); char buf[1024]; while(NULL!=fgets(buf,sizeof(buf),fp)){ printf("buf=%s",buf); } fclose(fp); 1 2, 3, 4, 5 L 3 L 4 buf[1024]

  4. ファイルの操作 (3) • 一度ファイルの最後まで読み込んだ後で、もう一度ファイルを最初から読み直すには? • fcloseしてから、もう一度fopenする。 • ファイルから読み込んだ情報を、配列に保存しておく。

  5. 関数の基本 • 変数に値を入れるもの • int ret = function(1,2); • 自分で関数を作る場合と、予め用意された関数を使う場合がある。

  6. 文字列処理関数: strncmp • 指定した数の文字を比較する。 • int ret = strncmp("abc","abc",3); • retに0が代入される。 • int ret = strncmp("abc","abcd",3); • retに0が代入される。 • int ret = strncmp("abc","abcd",4); • retに-1が代入される。 • int ret = strncmp("abd","abc",3); • retに1が代入される。

  7. 文字列処理関数: strstr • 文字列の中から、指定された文字列を捜す。 • char* ptr = strstr("abc","a"); • ptrに"a"の部分を指すポインタが代入される。 • char* ptr = strstr("abc","bc"); • ptrに"bc"の"b"の部分を指すポインタが代入される. • char* ptr = strstr("abc","d"); • ptrにNULLが代入される。

  8. 文字列処理: sscanf • 主に文字列を数値に変換する。 • int ivalue1,ivalue2; • intret = sscanf("5","%d",&ivalue1); • retに1が代入される。ivalue1に5が代入される。 • int ret = sscanf("5,6","%d,%d",&ivalue1,&ivalue2); • retに2が代入される。ivalue1、ivalue2に5,6が代入される。 • int ret = sscanf("abc","%d",&ivalue1); • retに0が代入される。ivalue1には何も入らない。

  9. 文字列処理の例 • char* ptr = strstr("str,1,name",","); • ptrに"str"の後ろの,のポインタが入る。 • ptrは、",1,name" という文字列ともいえる。 • ptr+1は、"1,name"という文字列になる。 • intivalue; • int ret = sscanf(ptr+1,"%d",&ivalue); • ivalueに1が入る。

More Related