It blew right past the gets line. Why? Because the scanf family has lots and lots of problems. Avoid them.
Specifically it tends to leave input on the buffer. In this case scanf("%s", name); read in all the text and left a newline on stdin. Then gets dutifully read that newline... and throws it out because that's how gets behaves. We can see this if we print name and content just before gets.
printf("name: '%s'\n", name);
printf("content: '%s'\n", content);
name: 'foo'
content: ''
Then your program dutifully writes nothing to the file.
Instead, use fgets to read entire lines, and sscanf to parse them. This avoids the danger of leaving input on the buffer.
printf("Enter file name:\n");
fgets(name, sizeof(name), stdin);
printf("Enter the content:\n");
fgets(content, sizeof(content), stdin);
fgets does not strip newlines, so you'll have to do that yourself. There's a variety of ways to do it.
void trim( char *string, char to_trim ) {
size_t len = strlen(string);
if( len == 0 ) {
return;
}
size_t last_idx = len -1;
if( string[last_idx] == to_trim ) {
string[last_idx] = '\0';
}
}
I prefer this approach because it only removes the newline if it's the final character.
Finally, always check your file operations. You're not checking if the fopen succeeded. If it fails for whatever reason you'll get another mysterious error. In my case the name I was using for testing already existed as a directory.
#include <string.h> // for strerror
#include <errno.h> // for errno
fp = fopen(name, "w");
if( fp == NULL ) {
fprintf(stderr, "Could not open '%s' for writing: %s.\n", name, strerror(errno));
return 1;
}