write() function in c does not write the data with spaces into file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

write() function in c does not write the data with spaces into file

write() function in c does not write the data with spaces into file Code: #include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<sys/stat.h> #include<sys/types.h> int main() { int fp; char fnm[50], data[1000]=""; printf("Enter the file name: "); scanf("%s",fnm); printf("\nEnter file data:\n"); scanf("%s",data); fp=open(fnm,O_CREAT | O_RDWR | O_APPEND,0777); if(fp==-1) { printf("\nError in opening file"); return 0; } write(fp,data,1000); close(fp); return 0; } Output: ./a.out Enter the file name: r Enter file data: rrrr yyyyyyyyyy yyyyyyyyy $ cat r rrrr Can someone help how can I accept the complete input using write() function itself

1st Apr 2021, 6:16 PM
Shweta Gare
Shweta Gare - avatar
3 Answers
+ 2
We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds first space. There are 3 method by which C program accepts string with space in the form of user input. Method 1 : Using gets Syntax : char *gets(char *str) Method 2 : we can use fgets Syntax : char *fgets(char *str, int size, FILE *stream) Method 3 : Using %[^\n]%*c inside scanf Example : scanf(“%[^\n]%*c”, str); Method 2 is recommended. edit: change the second scanf with fgets(data, 1000, stdin);
1st Apr 2021, 6:33 PM
Kashyap Kumar
Kashyap Kumar - avatar
0
If I replace the 2nd scanf by fgets(data,1000,stdin) The program terminates after accepting the file name & is creating a blank file.
1st Apr 2021, 6:51 PM
Shweta Gare
Shweta Gare - avatar
0
Thank you for your answers. I have changed the code by using fgets to take input from user. But the code is skipping the fgets and executing the remaining part of the program. I checked on few websites, majority of them sed that fgets is taking a new line character which is generated by the 1st scanf. M not sure how to remove this new line character.
2nd Apr 2021, 6:04 PM
Shweta Gare
Shweta Gare - avatar