1

I need to read in a formatted file that looks something like this.

Code: HARK

Name: Oscar

MRTE: Train

etc

At the moment my code looks like this.

FILE *file;
char unneeded[10];
char whitespace[2];
char actual[10];
file = fopen("scannertest.txt","r");
fscanf(file,"%s",unneeded); // this is the identifier and the colon (code:)
fscanf(file,"%[ ]",whitespace); // this takes in the white space after the colon.
fscanf(file,"%s",actual); // this is the value I actually need.
/**
* Do stuff with the actual variable
**/
fclose(file);

This way works for me but I don't think writing three fscanf()'s for each line in the text file is the best way to do it, especially as I will be doing it in a loop later.

I tried doing it like this:

fscanf(file, "%s %[ ] %s",unneeded,whitespace,real);

However this gave me weird symbols when I tried printing the output.

4

5 に答える 5

4

%sscanf 指定子はすでにスペースを無視しています。もしあなたがそうするなら

scanf("%s%s", unneeded, actual)

入力は "Code: HARK" で、unneeded"Code:"actualがあり、"HARK" があります。

警告:scanf面倒な機能です (安全に使用するのは「難しい」です)。より安全が必要な場合は、各文字列に受け入れることができる最大文字数を指定します (ゼロ ターミネータを覚えておいてください)。

scanf("%9s%9s", unneeded, actual); /* arrays defined with 10 elements */

を使用するのが最善fgetsですsscanf

別の回答へのコメントを読んだ後に編集する

そして、*常に* の戻り値を確認することを忘れないでくださいscanf

chk = scanf("%9s%9s", unneeded, actual);
if (chk != 2) /* error reading data */;
于 2009-12-12T02:12:58.977 に答える
1

あなたのコードは機能しません

fscanf(file,"%s",unneeded);
fscanf(file,"%[ ]",whitespace);
fscanf(file,"%s",actual);

と同じことはしません

fscanf(file,"%s %[ ] %s", unneeded, whitespace, actual);

機能的に同等です

fscanf(file,"%s%[ ]%s", unneeded, whitespace, actual); // No spaces in fmt string

HTH

于 2009-12-12T02:32:53.983 に答える
1

C では、ファイル関数はバッファー I/O を使用します。これは、fscanf が各呼び出しでディスクをヒットしないことを意味するため、1 回ではなく 3 回の呼び出しを使用した場合のパフォーマンスの低下は無視できるはずです。

ただし、最善の方法は、プログラムを動作させてから、遅すぎる場合は、パフォーマンスのボトルネックがどこにあるかを測定し、最初にそれらを修正することです。コードのどのセクションがパフォーマンスの問題を引き起こすかを推測しようとする価値はありません。

于 2009-12-12T02:21:27.787 に答える
0

コードを高速化する方法を探している場合は、ファイル全体、またはファイルのバッファーを読み込むことができます。一度にブロック全体を読み取る方が、必要に応じてデータを読み取るよりも高速です。

sscanfその後、読み取ったバッファで使用できます。

于 2009-12-12T02:00:00.667 に答える
0

私は時々 C でコーディングするのが恋しい病人です。うまくいくように見えるものを書きました:

test.txt の内容

Code: HARK
Name: Oscar
MRTE: Train

text.c の内容

#include <stdio.h>

#define MAX_LEN 256

int main(void)
{
  FILE *file;
  char str_buf[MAX_LEN + 1]; // One extra byte needed
                             // for the null character
  char unneeded[MAX_LEN+1];
  char actual[MAX_LEN+1];


  file = fopen("test.txt","r");

  while(fgets(str_buf, MAX_LEN + 1, file) != NULL)
  {
    sscanf(str_buf, "%s%s", unneeded, actual);
    printf("unneeded: %s\n", unneeded);
    printf("actual: %s\n", actual);
  }

  return 0;
}

コンパイルされたコードの出力:

unneeded: Code:
actual: HARK
unneeded: Name:
actual: Oscar
unneeded: MRTE:
actual: Train
于 2009-12-12T02:25:44.550 に答える