嗯,有一段时间没有在<stdio.h>图书馆这样做了。前段时间,我为此写了一篇文档。它实际上仍然在这里漂浮在网上。我重读了一遍,还是不错的。(看起来有人甚至在几年前发表了一条我没有回应的评论......哎呀)。不过,您可能也想阅读它。
使用 C stdio 库,您几乎可以做任何事情,但由于缓冲区溢出和处理不当的错误处理,它可能会面临危险。但它可以做到(但我个人的偏好是如果可以的话使用perl)。
您对此并没有真正指定太多,但我会试一试。我认为是这样的:
#include <stdio.h>
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)
int main()
{
FILE *fp;
fp = fopen("vectors.lst", "r");
if (fp == NULL) {
printf("Failed to open\n");
/* Exit return of non-zero to indicate an error to calling process */
return 1;
}
#define MAX_BUFFER 1024
char passedstring[MAX_BUFFER+1];
passedstring[MAX_BUFFER] = 0;
int correctvalue = 0;
int position;
position = 0;
/* " " - ignore any leading whitespace if any
* "(" - match open parenthesis
* "%" STRINGIZE(MAX_BUFFER) "[^)]" - store up to MAX_BUFFER chars
* that are not ')'
* ")" - match close parenthesis
* " " - match any whitespace if any
* "%d" - store int value
* "%n" - store current read byte from fscanf(), if parse fails, store
* doesn't occur. Ensures that everything has been read in.
**/
while(fscanf(fp, " (%" STRINGIZE(MAX_BUFFER) "[^)]) %d%n"
, passedstring, &correctvalue, &position) != EOF
&& position > 0)
{
printf("%s, %d\n", passedstring, correctvalue);
position = 0;
}
printf("End %d", position);
/* Exit code returned here. Not advised to use exit() for something like this. */
return 0;
}
#undef MAX_BUFFER
不确定您的外部 for 循环是做什么用的。这只是读取直到它到达文件的末尾,或者如果一个字符串太大以至于它比缓冲区大。如果你想做一些恢复代码,我会留给你。
我通过编译器运行它。现在已验证可以正常工作。