fscanf() 只拾取文件的第一行 [英] fscanf() only picking up first line of file
问题描述
我有一个制表符分隔文件,我正在尝试将其转换为制表符分隔文件.我正在使用 C.我一直在尝试读取文件的第二行.现在我只有几万行重复第一行.
I have a tab delimited file that I am trying to convert to a tab delimited file. I am using C. I am getting stuck on trying to read the second line of the file. Now I just have an tens of thousand of lines repeating the first line.
#include <stdio.h>
#include <string.h>
#define SELLERCODE A2LQ9QFN82X636
int main ()
{
typedef char* string;
FILE* stream;
FILE* output;
string asin[200];
string sku[15];
string fnsku[15];
int quality = 0;
stream = fopen("c:\\out\\a.txt", "r");
output = fopen("c:\\out\\output.txt", "w");
if (stream == NULL)
{
perror("open");
return 0;
}
for(;;)
{
fscanf(stream, "%[^\t]\t%[^\t]", sku, fnsku);
printf("%s\t%s\n", sku, fnsku);
fprintf(output, "%s\t%s\t%\t%s\t%s\t%i\n", sku, fnsku, asin, quality);
}
}
推荐答案
首选 fgets()
读取输入并解析程序中的行,例如使用 sscanf()
或 strtok()
.
Prefer fgets()
to read the input and parse the lines in your program, using, for example, sscanf()
or strtok()
.
fscanf
是出了名的难以使用.
您的 fscanf 在第一行之后没有执行任何转换.
它读取字符直到 TAB,然后忽略 TAB,并读取更多字符直到下一个 TAB.在第二次循环中,sku
没有数据:第一个字符是 TAB.
fscanf
is notoriously difficult to use.
Your fscanf is not performing any conversions after the first line.
It reads characters up to a TAB, then ignores the TAB, and reads more characters up to the next TAB. On the 2nd time through the loop, there is no data for sku
: the 1st character is a TAB.
请检查返回值.它有很大帮助.
chk = fscanf(stream, "%[^\t]\t%[^\t]", sku, fnsku);
/* 2 conversions: sku and fnsku */
if (chk != 2) {
/* something went wrong */
}
这篇关于fscanf() 只拾取文件的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!