Search code examples
cfgetsuserspace

fgets that doesn't stop at spaces or linebreaks


I'm writing a user space program and I want to send a text file content to the kernel module. The text file isnt to long so instead of sending line by line I rather send all the text in one string.

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;

I noticed that fget break at space and line break. Is there another function that reads text file and save it in a string I can use?

The text file len is below 50*256 char.


Solution

  • Obviously you are not regarding any line breaks or other breaks, so as comment says:

    If you don't care about lines, use fread() rather than fgets().

    The code is as follows:

    char *rules = malloc(sizeof(50*256*sizeof(char))); 
    /* ... */
    memset(rules, 0, 50 * 256);
    errno = 0;
    /* read one byte less to make string functions happy */
    size_t len = fread(rules, 1, 50*256 - 1, rules_text_file)
    if (errno) {
        return -1;
    }