Cのファイルから1行を読み取り、入力数を抽出します
input.datファイルがあります。このファイルには、次の3行があります。
1 2 3
5 7 10 12
8 9 14 13 15 17
Cを使用して3行のうちの1つを読み取り、要素の数を返します。たとえば、2行目5 7 10 12
をメモリに読み込み、2行目の値の数である。を返します4
。私のコードは以下です...
#include <stdio.h>
#include <stdlib.h>
#define STRING_SIZE 2000
int main() {
FILE *fp = fopen("in.dat", "r");
char line[STRING_SIZE];
int lcount = 0, nline = 1, sum = 0, number;
if (fp != NULL) {
while (fgets(line, STRING_SIZE, fp) != NULL) {
if (lcount == nline) {
while (sscanf(line, "%d ", &number)) {
sum++;
}
break;
} else {
lcount++;
}
}
fclose(fp);
}
exit(0);
}
このコードを実行すると、デッドループのように停止することはありません。ここでの問題は何ですか?
回答
ループwhile (sscanf(line, "%d ", &number))
は、行の最初の数値を解析し続けます。
strtol
代わりに使用する必要があります:
#include <stdio.h>
#include <stdlib.h>
#define STRING_SIZE 2000
int main() {
FILE *fp = fopen("in.dat", "r");
char line[STRING_SIZE];
int lcount = 0, nline = 1;
if (fp != NULL) {
while (fgets(line, STRING_SIZE, fp) != NULL) {
if (lcount == nline) {
char *p = line, *q;
int count = 0;
for (;;) {
long val = strtol(p, &q, 0); // parse an integer
if (q == p) {
// end of string or not a number
break;
}
// value was read into val. You can use it for whatever purpose
count++;
p = q;
}
printf("%d\n", count);
break;
} else {
lcount++;
}
}
fclose(fp);
}
return 0;
}
を使用して正しい道を考えていましたsscanf()
が、欠けていたパズルの唯一の部分は、line
への次の呼び出しで行の次の値を読み取るようにオフセットを適用する方法sscanf()
です。これを行うにはsscanf()
、"%n"
変換を使用するための各呼び出しで消費された文字数を追跡します(によって返される変換カウントには追加されませんsscanf()
)。たとえば、開いているファイルストリームから行を読み取るとfp
、次のことができます。
#define MAXC 1024 /* if you need a constant, #define one (or more) */
...
char line[MAXC] = ""; /* buffer to hold each line */
...
while (fgets (line, MAXC, fp)) { /* reach each line in file */
int offset = 0, /* offset in line for next sscanf() read */
nchr = 0, /* number of char consumed by last read */
val, /* integer value read with sscanf() */
nval = 0; /* number of values read in line */
/* conververt each integer at line + offset, saving no. of chars consumed */
while (sscanf (line + offset, "%d%n", &val, &nchr) == 1) {
printf (" %d", val); /* output value read */
offset += nchr; /* update offset with no. chars consumend */
nval++; /* increment value count */
}
printf (" - %d values\n", nval); /* output no. values in line */
}
(注: 変換が失敗したstrtol()
場合よりも優れたエラーレポートを提供しますsscanf()
)
プログラムの最初の引数として提供されたファイル名から読み取る(またはstdin
引数が指定されていない場合はデフォルトでから読み取る)例と組み合わせると、次のことができます。
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (int argc, char **argv) {
char line[MAXC] = ""; /* buffer to hold each line */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (line, MAXC, fp)) { /* reach each line in file */
int offset = 0, /* offset in line for next sscanf() read */
nchr = 0, /* number of char consumed by last read */
val, /* integer value read with sscanf() */
nval = 0; /* number of values read in line */
/* conververt each integer at line + offset, saving no. of chars consumed */
while (sscanf (line + offset, "%d%n", &val, &nchr) == 1) {
printf (" %d", val); /* output value read */
offset += nchr; /* update offset with no. chars consumend */
nval++; /* increment value count */
}
printf (" - %d values\n", nval); /* output no. values in line */
}
if (fp != stdin) /* close file if not stdin */
fclose (fp);
}
使用例/出力
ファイル名に表示するデータを使用すると、次のようになりますdat/nvals.txt
。
$ ./bin/fgetsnvals dat/nvals.txt
1 2 3 - 3 values
5 7 10 12 - 4 values
8 9 14 13 15 17 - 6 values
物事を見て、さらに質問があれば私に知らせてください。
chqrlieの答えの少しクリーンなバージョン。文字列から始めました。それが、質問の実際の内容fgets()
です。
sscanf()
文字列をステップスルーせず、常に最初から読み取ります。
strtol()
long int
最初の空白を無視して、文字列の先頭でaを探します。スキャンを停止した場所のアドレスを返します。
のマニュアルにstrtol()
は、変換エラーがないかerrnoをチェックする必要があると記載されています。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define STRING_SIZE 2000
int main(void)
{
char line[STRING_SIZE] = "5 7 10 12";
char* start = line;
char* end;
int count = 0;
while(1)
{
/**
* strtol() look for long int in beginning of the string
* Ignores beginning whitespace
*
* start: where to strtol() start looking for long int
* end: where strtol() stops scanning for long int
*/
errno = 0; // As strol() manual says
strtol(start, &end, 0);
if (errno != 0)
{
printf("Error in strtol() conversion.\n");
exit(0);
}
if (start == end) break; // Quit loop
start = end;
count++;
}
printf("count: %d\n", count);
return 0;
}