-1

I had made a program that creates a file with name given by a user.

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
       int g;
       char file[15];
       fgets(file,15,stdin);
       g=open(file,O_CREAT | O_WRONLY,__S_IWRITE);


}

But it creates a file with a filename with some garbage character at the end. How can I correct this?

here is sample run:

$ ./a.out
coolfile.txt
$ ls
a.out  coolfile.txt?  test.c

the same program but just using gets function gives correct filename but I had heard that gets should not be used.

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27
  • Currently, there is no call to a write function in the code and please show us the content of the file. Also, you should always close your file descriptors after opening one. – PhilMasteG Aug 06 '17 at 04:36
  • 2
    `fgets()` retains the `'\n'`. Likely that character is a problem for printable file names – chux - Reinstate Monica Aug 06 '17 at 04:37
  • @PhilippGrassl File is empty.I had used cat command –  Aug 06 '17 at 04:39
  • Add `#include ` then just `fgets(file,sizeof file,stdin); size_t len = strlen (file); if (len && file [len - 1] == '\n') file[--len] = 0; ...` That will overwrite any `'\n'` with a *nul-terminating* character (`'\0'` or the simple equivalent '0'). – David C. Rankin Aug 06 '17 at 04:56
  • Possible duplicate of [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – Dima Chubarov Aug 06 '17 at 04:56

2 Answers2

1

fgets() stores the newline at the end of each line in the result. So you are creating files whose names end with a newline character. To fix it, simply check the last character and set it to '\0' if it was '\n'.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

fgets stores \n at th end of each line thus you need remove that \n

to dot this use strcspn function

thus your code should look like this

 #include <stdlib.h>
 #include <stdio.h>
 #include <fcntl.h>
 #include <string.h>
 int main()
  {
    int g;
    char file[15];
    fgets(file,15,stdin);
    file[strcspn(file, "\n")] = 0;
    g=open(file,O_CREAT | O_WRONLY,__S_IWRITE);
  }

You can see more information about strcspn on :- https://www.tutorialspoint.com/c_standard_library/c_function_strcspn.htm

Also refer this :- Removing trailing newline character from fgets() input