本文介绍了如何读取标准输入字符串变量,直到EOF用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到总线错误尝试读取标准输入的char * 变量。
我只是想读的东西全过来标准输入并把它首先进入一个变量,然后继续变量工作。

I am getting "Bus Error" trying to read stdin into a char* variable.I just want to read whole stuff coming over stdin and put it first into a variable, then continue working on the variable.

我的code是如下:

char* content;
char* c;
while( scanf( "%c", c)) {
 strcat( content, c);
}

fprintf( stdout, "Size: %d", strlen( content));

但不知何故,我总是得到通过调用猫的test.txt返回总线错误|的myapp ,其中的myapp 高于编译code。

But somehow I always get "Bus error" returned by calling cat test.txt | myapp, where myapp is the compiled code above.

我的问题是我如何读标准输入直到EOF到一个变量?当您在code看到的,我只是想打印输入过来标准输入的大小,在这种情况下,它应该是等于文件的大小的test.txt

My question is how do i read stdin until EOF into a variable? As you see in the code, I just want to print the size of input coming over stdin, in this case it should be equal to the size of the file test.txt.

我以为只是使用 scanf函数就足够了,也许缓冲方式来阅读标准输入

I thought just using scanf would be enough, maybe buffered way to read stdin?

推荐答案

首先,你传递未初始化的指针,这意味着 scanf函数的strcat 会写你没有自己的记忆。其次, strcat的预计两个空结尾的字符串,而C只是一个字符。这将再次导致它来阅读你没有自己的记忆。你不需要scanf的,因为你没有做任何实际的处理。最后,每次读一个字符是不必要的缓慢。这里有一个解决方案的开始,使用最后一个字符串一个可调整大小的缓冲区,并为与fgets通话的固定缓冲

First, you're passing uninitialized pointers, which means scanf and strcat will write memory you don't own. Second, strcat expects two null-terminated strings, while c is just a character. This will again cause it to read memory you don't own. You don't need scanf, because you're not doing any real processing. Finally, reading one character at a time is needlessly slow. Here's the beginning of a solution, using a resizable buffer for the final string, and a fixed buffer for the fgets call

#define BUF_SIZE 1024
char buffer[BUF_SIZE];
size_t contentSize = 1; // includes NULL
/* Preallocate space.  We could just allocate one char here,
but that wouldn't be efficient. */
char *content = malloc(sizeof(char) * BUF_SIZE);
if(content == NULL)
{
    perror("Failed to allocate content");
    exit(1);
}
content[0] = '\0'; // make null-terminated
while(fgets(buffer, BUF_SIZE, stdin))
{
    char *old = content;
    contentSize += strlen(buffer);
    content = realloc(content, contentSize);
    if(content == NULL)
    {
        perror("Failed to reallocate content");
        free(old);
        exit(2);
    }
    strcat(content, buffer);
}

if(ferror(stdin))
{
    free(content);
    perror("Error reading from stdin.");
    exit(3);
}

编辑:沃孚提到,在你输入一个NULL会导致使用与fgets时的字符串,pmaturely终止$ P $。 是一个更好的选择,如果可用,因为它处理内存的分配和做没有问题与NUL输入。

As Wolfer alluded to, a NULL in your input will cause the string to be terminated prematurely when using fgets. getline is a better choice if available, since it handles memory allocation and does not have issues with NUL input.

这篇关于如何读取标准输入字符串变量,直到EOF用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:55