Reputation: 1
#include <stdio.h>
#include <string.h>
void main() {
FILE* fp;
char line[1024];
char filename[1024];
int length;
int counter=0;
while (1) {
// fopen(filename, "w");
int op = 0;
printf("1. new file");
scanf("%d", &op);
switch (op) {
case -1: break;
case 1:
printf("filename>>");
scanf("%s", filename);
length = strlen(filename);
printf("length = %ld \n", strlen(filename));
filename[length] = '.';
filename[length + 1] = 't';
filename[length + 2] = 'x';
filename[length + 3] = 't';
filename[length + 4] = '\0';
fp=fopen(filename, "w");
while (fgets(line, sizeof line, stdin) != NULL)
{
if (line[0] == 'q' || line[0] == 'Q')
{
printf("end of line \n");
fclose(fp);
break;
}
else
fputs(line, fp);
}
}
}
}
I made this code to make text file with what I want. but the problem is, when I run this program, it writes input starting from the second line, not the first.
Why is this happening? I want to write input starting from the first line. How to change this code to write on the first line?
Upvotes: 0
Views: 89
Reputation: 3699
scanf("%s", filename);
When you input the name of file from keyboard, you type the filename then hit ENTER. The scanf
function read filename
but does not consume the ENTER character. Then when you use fgets
, it will read this ENTER character then write a blank line into your file.
To solve this problem, you can use getchar()
after scanf("%s", filename);
to consume the enter character. You should add 1023
before %s
in scanf
function: Disadvantages of scanf.
scanf("%1023s", filename);
getchar();
Or you can use fgets
instead:
fgets(filename, sizeof(filename), stdin);
One more thing, the break
in switch
statement does not help you to quit the first while
loop (while (1) {...}
). You should use one condition to exit this loop, for example:
char ch = 'a';
while (ch != 'q') {
...
switch (op) {
case -1: ch = 'q'; break; // type -1 will exit the first while loop.
The switch
should have the default
case for the exception.
switch (op) {
...
default:
// handle the exception here.
Upvotes: 1
Reputation: 7882
Likely reason is that you are using fgets just after scanf on standard input.
See Using scanf and fgets in the same program?.
Upvotes: 0