[英]Trouble using fscanf in C
我在使用fscanf从文件中读取字符串并打印每个字符串中的字母数时遇到困难。 该文件如下所示:
ACGTTTTAAGGGCTGAGCTAGTCAGTTCATCGCGCGCGTATATCCTCGATCGATCATTCTCTAGCAC
(文件中的每一行都是一个单独的字符串,每个字符串中的最大字符数为241)
这是我尝试过的方法,但似乎没有用:
include <stdio.h>
FILE *input;
int main ()
{
int i=0, count=0;
char sequence[241];
/*reads DNA sequence from input, stores it in an array, and returns the # of
letters read as an int */
input=fopen("dna_input.dat", "r");
while (fscanf(input, "%c", &sequence[i++]) != EOF)
count++;
printf ("The number of letters in a sequence is: %d\n", count);
return 0;
}
您的代码中没有任何内容可以识别行的结尾-只能识别文件的结尾。 另外,您正在将整个文件读入一个缓冲区,该缓冲区仅够一行。 而且,您打算打印每一行的结果还是仅打印整个文件的结果? 因为它在做后者(如果它不首先从缓冲区溢出中崩溃)。
假设每行:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *input;
char sequence[242];
input = fopen("dna_input.dat", "r");
while (fgets(sequence, 242, input) != NULL)
{
printf("The number of letters in a sequence is: %d\n",
strlen(sequence) - 1); /* don't count trailing \n */
}
fclose(input);
return 0;
}
是的,很抱歉,我在这里找不到fscanf()的用途。 :)
对读取和处理字符的代码进行一些更改:
#include <stdio.h>
FILE *input;
int main ()
{
int i=0, count=0;
char sequence[241];
/*reads DNA sequence from input, stores it in an array, and returns the # of
letters read as an int */
input=fopen("dna_input.dat", "r");
int c ;
while ( (c = fgetc(input) != EOF))
{
if ( c != '\n')
{
sequence[i++] = c;
count++;
}
else
{
printf ("The number of letters in a sequence is: %d\n", count);
/* Terminate the sequence with a null character */
sequence[i] = '\0';
/* Reset the counters */
i = 0;
count = 0;
}
}
/* Take care of the last line if it does not end in a newline character */
if ( count > 0 )
{
printf ("The number of letters in a sequence is: %d\n", count);
}
return 0;
}
另外,如果您希望sequence
为以null终止的字符串,则可能需要将其创建为242个字符的数组,最后一个用于存储终止的null字符。
这里的主要问题是fscanf不会返回读取的字符,因此它将永远不会返回EOF。 另外,要记住的一点是,换行符(\\ n)被视为字符,因此您可能需要将其过滤掉。 另一个更安全的选择是仅使用fgets()来读取您的输入:
编辑:由于您想知道注释中的内容,因此您需要知道的一件事是字符串的结构。 字符串是一个以0 aka'\\ 0'结尾的字符数组(不要与'0'混淆)。 手动查找字符串长度的方法是执行以下操作:
char *str = "Hello, world!";
int len = 0;
while (str[len] != 0)
len++;
本质上,您正在执行的操作是遍历字符串,并且每次到达不为零的字符时,长度都会增加,而到达零时,字符长度会停止。 希望这可以帮助!
fscanf
返回成功匹配和分配的项目数,该数量可以少于所提供的数量,在早期匹配失败的情况下甚至为零。 但是,如果在第一次成功转换或匹配失败发生之前到达输入结束,它将返回EOF
。 另外,格式字符串中的%c
转换说明符匹配所有字符,包括空格。
fscanf
的以上两个功能意味着,仅当fscanf
到达文件末尾时, while
循环条件才为false
,但在此之前,如果文件长度超过241
字符,则它可能会超出sequence
指向的缓冲区。 这是未定义的行为,很可能会导致段错误。
您应该改用fgets
。 fgets
还读取换行符,如果遇到换行符,则将其存储在缓冲区中,然后再返回。 文件中的所有行都将以换行符终止,但最后一行可能不包含终止换行符。 另外,您应该检查文件I / O错误。
#include <stdio.h>
int main(void) {
int len;
char sequence[241 + 1]; // +1 for the terminating null byte
FILE *input = fopen("dna_input.dat", "r");
if(input == NULL) {
printf("Error in opening the file\n");
return -1;
}
while(fgets(sequence, 242, input) != NULL) {
len = strlen(sequence);
if(sequence[len-1] == '\n')
--len;
printf("The number of letters in the sequence is: %d\n", len);
}
fclose(input);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.