fgets 不会在空格或换行符处停止

问题描述 投票:0回答:1

我正在编写一个用户空间程序,我想将文本文件内容发送到内核模块。文本文件不太长,因此我不是逐行发送,而是将所有文本发送到一个字符串中。

FILE *rules_text_file;
char *rules = (char *)malloc(sizeof(50*256*sizeof(char))); 
....
if (fgets(rules, 100, rules_text_file) == NULL) {
    return -1;
}
printf("%s\n",rules);  
          
fclose(rule_dev_file);
fclose(rules_text_file);
free(rules);
return 0;

我注意到 fget 在空格和换行处中断。是否有另一个函数可以读取文本文件并将其保存在我可以使用的字符串中?

文本文件长度小于50*256字符。

c fgets userspace
1个回答
0
投票

最好的 fgets 是你自己编写的。我也厌倦了 fgets() 限制等。例如,有一次我正在阅读lots的文件,并且总是必须添加代码来删除换行符(' ') 字符。

最后,我编写了这段代码,它在换行符处停止读取(如 std lib fgets() )——但将换行符存储到缓冲区中。

如果您不希望此代码在换行符处中断/停止读取,则只需注释掉

done_reading = 1;
下面出现的行,该行出现在
switch()
case '\n':

最美好的祝愿和快乐的编码。

/*-------------------------------------------------------------------------
char *myfgets(buffer, count, stream) - input string from a stream

Purpose: 
    Read a string from the input stream argument and store it in
    buffer. myfgets() reads characters from the current stream position to 
    and including the first newline character ('\n'), to the end of the 
    stream, or until the number of characters read is equal to count - 1, 
    whichever comes first. 

    The result stored in buffer is appended with a NUL ('\0') character. 
    The newline character('\n'), if read, is NOT included in the buffer.
    The carriage return('\r'), if read, is also NOT included in the buffer.

Entry:
       char *buffer- pointer to place to store bytes
       int count - max characters to place in buffer
       FILE *fp - stream to read from

Exit:
       returns buffer with text read from file.
       if count <= 0 return NULL
       returns NULL if error or end-of-file found immediately

*------------------------------------------------------------------------*/
char *myfgets (char *buff, int count, FILE *fp )
{
char *ptr = buff;
int ch, done_reading = 0; 

    if(!buff || !fp || count < 1)
        return NULL;

    while (count-- > 1 && !done_reading)
    {
        ch = fgetc(fp);

        switch(ch)
        {
            /* Carriage return: 0x0D   Linefeed: 0x0A
            ** In MSDOS/Windows each line ends with sequence 0D,0A (\r,\n); */
            case '\n':      /* Never accumulate linefeed into the buffer ... */
                done_reading = 1;  /* Comment-out this line and reading will not stop here! */
            case '\r':      /* Never accumulate carriage return into the buffer.*/
            break;

            case EOF:
                if (ptr == buff)
                    return NULL;
                done_reading = 1;

            default:
               *ptr++ = (char) ch;
            break;
        }
    }
    *ptr = '\0'; /* cap it */
    return(buff);
}
© www.soinside.com 2019 - 2024. All rights reserved.