-
writing to file
hello guys
i need some help to this code:
Code:
#include<stdio.h>
void main (void)
{
char input;
FILE *file;
file = fopen ("self.dat", "w+");
if (file==NULL)
{
printf("an error occured!\n");
}
else
{
printf("what shall be written into the file: \n");
scanf("%c", &input);
fprintf(file, "%c", input);
printf("\nclosing file!\n");
fclose(file);
}
}
everything works fine. but when the program asks for the text that shall be written to the file and i type something like:
"hello world i love you" and take a look at the file, there only exists the first word. in this case "hello".
how do i configure the source code that its possible to safe a whole sentence.(or even more than this!).
thanks for the help
threadhead
-
there is even one more problem!
when i view the file there i can see only the first letter typed in.
:confused:
-
You are only reading one char.
you use a char as a buffer and %c conversion in scanf() so its hardly surprising.
Read your helpfiles or text book and look up the function fgets() and make your buffer a char array.
-
if i use
Code:
char input[256];
........
scanf("%s", &input);
fprintf(file, "%s", input);
instead of the other modification it only reads the first word not more than this.
but i defined an array :rolleyes:
-
scanf stops at whitespace. u can tell it not to but i can never remember the conversions without looking it up.Salem will know. I find it much easier to use fgets()
-
funny :D
just replace scanf() with fgets()?
Code:
#include<stdio.h>
void main (void)
{
char zeichen[256];
FILE *datei;
datei = fopen ("self.dat", "w+");
if (datei==NULL)
{
printf("an error occured!\n");
}
else
{
printf("what shall be written into the file: \n");
fgets("%s", &zeichen);
fprintf(datei, "%s", zeichen);
printf("\nclosing file!\n");
fclose(datei);
}
}
doesnt work either :(
-
do u have helpfiles?
can u search these boards?
got a book?
thats appalling use of fgets....
char* fgets( char* buffer,int buffer_size,FILE* stream)
so to get from the kb...
fgets(your_buffer,your_buffer_size,stdin);
one small gotcha. You will maybe have to replace the newline in the string with a null char as fgets will put the newline in your array. Theres at least 4 ways of doing this mentioned in recent threads. do some research. thats what the search button is for.