I want to write multiple lines in C , and when I enter a empty line , to exit the writing , so far I'm writing only one word in text...
printf("Enter new file name ,or the file which you want to edit: ");
scanf("%s",filename);
snprintf(buffer1, sizeof(buffer1), "C:\\Proiect\\%s.txt", filename);
FILE *OutFile = fopen(buffer1,"w");
scanf("%s",write_in_file);
fprintf(OutFile,"%s",write_in_file);
fclose(OutFile);
printf("File %s created!",filename);
EDIT , I don't know why , after I'm running this code , after I 'm writing first word my code is crashing...
printf("Enter new file name ,or the file which you want to edit: ");
scanf("%s",filename);
snprintf(buffer1, sizeof(buffer1), "C:\\Proiect\\%s.txt", filename);
char line[256];
FILE *OutFile = fopen(buffer1,"w");
do {
fgets(line,256,stdin);
fprintf(OutFile,line);
//Your code to store the line to the file.
}while(line[0] != '\n');
fclose(OutFile);
答案 0 :(得分:1)
Use fgets()
. As the documentations says,
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.
The only thing you need to remember is that there is an upper bound on the line size. So for instance if the max size of the line your program will accpet is 255(+1 for \0
), here is what your code should look like
char line[256];
do {
fgets(line,256,stdin);
//Your code to store the line to the file.
}while(line[0] != '\n')