After the line "command(system)", the next lines are not running. A new file "test1" is created but the next lines do no execute.
Using my linux Ubuntu terminal, I am trying to write a C program for opening a new file. Since the new file is created, it means that the system() function is working. But it does not stop executing.
If I close the terminal, it says "process is running". How do I stop the process? I do not get the linux terminal’s line for command after a new file is created.
#include <stdio.h>
#include <stdlib.h>
int main() {
char filename[50];
printf("Enter the filename: ");
scanf("%s", filename);
// Create and open the file using the cat command
char command[100];
sprintf(command, "cat > %s", filename);
system(command);
printf("File '%s' created and opened.n", filename);
return 0;
}
2
Answers
They do not execute yet. That’s because the
cat
command you are running viasystem()
is waiting for input from its standard input. Thesystem()
function will not return untilcat
terminates. Typing Ctrl-D in the terminal window should make it stop waiting.If all you want to do is create an empty file, then changing the command to redirect
cat
‘s standard input would be one way to go about that:But if that’s really all you want to do, then it would be more idiomatic to use
touch
instead ofcat
:It’s not entirely clear what your goal is here. If you just want to create an empty file, you can do it using the regular C standard library file functions, without calling out to a shell with
system()
.Something like this might suffice:
If the file already exists, but you want to "empty" it:
Calling
system()
to run some commands with file redirection is extremely non-portable and probably pointless. If you want to go down that path, just make a bash (or Python, or Ruby…) script.