0

I'm trying to store a string from the user's inpute ( with scanf()) in a .txt file by using open(), write(). I do use a buffer to store the input, then send it to the file with write(). The problem is that i can't store any " " which is a spacebar's character... It does only store the characters before the space. But i actually want to keep writing until the '\n'. here's my code :

 void writing(char* argument){
    int desc_fich=-1, nb_lus=-1, nb_write=-1;
    
    printf("Enter the words : ");

        char entry[50];

        for (int i=0;i<50; i++){
            entry[i]= '\0'; 
        }

        scanf("%s", &entry);

        int i=0;
        int number=0;

        while ( entry[i] != '\0' ){

            number++;
            i++;
        }

        desc_fich = open(argument, O_WRONLY | O_CREAT | O_APPEND);

        nb_write = write(desc_fich, entry, nombre); 


        close(desc_fich);
}

`
Anis AIT
  • 31
  • 1
  • 1
  • 7
  • 3
    That's what `scanf()` does, it "Matches a sequence of non-white-space characters". Are you sure you don't want to just use `fgets()` instead to read a full line at one go if you want to read until a `\n` anyway? – ilkkachu Mar 01 '21 at 23:22
  • 1
    Use `fgets` to read a line, and [remove the newline](https://stackoverflow.com/a/28462221/3386109) if you wish. – user3386109 Mar 01 '21 at 23:22
  • 1
    `scanf("%[^\n]", entry);` instead of `scanf("%s", &entry);`? (don't forget to remove the extra `&`) – MikeCAT Mar 01 '21 at 23:24
  • 1
    Whoever told you to use `scanf` may have given you the wrong impression that it's good for many things. Actually it's at all good for only three limited things: (1) reading single integers, (2) reading single floating-point numbers, and (3) reading single strings not containing spaces. Anything else, it's no good at all for. (And, in the long run, it's not actually all that good at reading ints, floats, and spaceless strings, either.) – Steve Summit Mar 01 '21 at 23:36
  • 1
    `scanf("%[^\n]", entry);` fails to read an empty line. Without a width limit, it is worse than [`gets()`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – chux - Reinstate Monica Mar 02 '21 at 00:36

1 Answers1

2

scanf("%s", &entry); first reads and skips over all leading white-space. Then reads and saves, perhaps too many, non white-space characters.

Instead of scanf(), use fgets() to read a line.

   // scanf("%s", &entry);
   if (fgets(entry, sizeof entry, stdin)) {
     ...
     // nb_write = write(desc_fich, entry, nombre);
     nb_write = write(desc_fich, entry, strlen(entry));
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256