如何检查使用 C 中的 fread 函数输入的字符数
char buffer[101];
int bytesRead = fread(buffer, sizeof(char), 100, stdin);
输入 100 个字符会产生预期的结果。然而,输入超过 100 个会导致害怕只删除其他字符,所以我永远看不到用户实际输入的内容。我知道还有其他方法没有使用 fread 但我实际上必须在这里使用它,所以我可以检查用户输入,如果输入长度 >100,我可以给出缓存已超出的错误。
在这种情况下,您应该使用条件指令(如(“if”)),但您需要函数 fread() 返回的值,由于函数结构会切断其他字符,因此您没有该值。如果你的想法是获取输入并保存它,你应该用 ("fopen("filename","mode")) 打开两个文件,第一个在 "r" 模式下,第二个在 "a" 模式下,并用限制为 100 的 for 循环实际上是将第一个文件的输入复制并粘贴到第二个文件。希望对您有所帮助。
如果你还希望程序在输入太短时拒绝输入并打印错误信息,那么函数
fread
的问题如下:
函数
fread
不会返回,直到发生以下情况之一:
没有办法让
fread
遇到换行符就返回
因此,如果您坚持使用函数
fread
,那么解决问题的唯一方法就是使用fread
一次读取一个字符,直到遇到换行符。然而,这没有意义。
fgets
而不是fread
,例如像这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//forward declaration
void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
int main( void )
{
char buffer[30];
get_line_from_user( "Please enter a string: ", buffer, sizeof buffer );
printf( "Input was successful.\nYou entered: %s\n", buffer );
}
//This function will read exactly one line of input from the
//user. It will remove the newline character, if it exists. If
//the line is too long to fit in the buffer, then the function
//will automatically reprompt the user for input. On failure,
//the function will never return, but will print an error
//message and call "exit" instead.
void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
{
for (;;) //infinite loop, equivalent to while(1)
{
char *p;
//prompt user for input
fputs( prompt, stdout );
//attempt to read one line of input
if ( fgets( buffer, buffer_size, stdin ) == NULL )
{
printf( "Error reading from input!\n" );
exit( EXIT_FAILURE );
}
//attempt to find newline character
p = strchr( buffer, '\n' );
//make sure that entire line was read in (i.e. that
//the buffer was not too small to store the entire line)
if ( p == NULL )
{
int c;
//a missing newline character is ok if the next
//character is a newline character or if we have
//reached end-of-file (for example if the input is
//being piped from a file or if the user enters
//end-of-file in the terminal itself)
if ( (c=getchar()) != '\n' && !feof(stdin) )
{
if ( ferror(stdin) )
{
printf( "Error reading from input!\n" );
exit( EXIT_FAILURE );
}
printf( "Input was too long to fit in buffer!\n" );
//discard remainder of line
do
{
c = getchar();
if ( ferror(stdin) )
{
printf( "Error reading from input!\n" );
exit( EXIT_FAILURE );
}
} while ( c != '\n' && c != EOF );
//reprompt user for input by restarting loop
continue;
}
}
else
{
//remove newline character by overwriting it with
//null character
*p = '\0';
}
//input was ok, so break out of loop
break;
}
}
这个程序有以下行为:
Please enter a string: This is a string longer than 30 characters.
Input was too long to fit in buffer!
Please enter a string: This is a shorter string.
Input was successful.
You entered: This is a shorter string.