1

我需要读取一个看起来像这样的格式化文件。

代码:HARK

姓名:奥斯卡

MRTE:火车

ETC

目前我的代码看起来像这样。

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);

这种方法对我有用,但我不认为为文本文件中的每一行编写三个 fscanf() 是最好的方法,特别是因为我稍后将在循环中这样做。

我试着这样做:

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

然而,当我尝试打印输出时,这给了我奇怪的符号。

4

5 回答 5

4

scanf说明%s符已经忽略了空格。如果你这样做

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

输入是“代码:HARK”,unneeded将有“代码:”和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

在 C 中,文件函数使用缓冲 I/O。这意味着 fscanf 不会在每次调用时访问磁盘,因此使用 3 次调用而不是 1 次调用的性能损失应该可以忽略不计。

但是,最好的办法是让您的程序正常工作,然后如果它太慢,请测量性能瓶颈所在并首先解决这些问题。尝试猜测哪些代码段会导致性能问题是不值得的。

于 2009-12-12T02:21:27.787 回答
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

高温高压

于 2009-12-12T02:32:53.983 回答
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 回答
0

如果您正在寻找加快代码速度的方法,您可以读取整个文件或文件的缓冲区。一次读取整个块比根据需要读取数据要快。

然后,您可以sscanf在您读取的缓冲区上使用。

于 2009-12-12T02:00:00.667 回答