skip to Main Content

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;
}

In the directory, a new file named "test1" is created but in the terminal, as you can see, the code doesn’t finish executing/doesn’t stop.

2

Answers


  1. After the line "command(system)", the next lines are not running. A new file "test1" is created but the next lines do no execute.

    They do not execute yet. That’s because the cat command you are running via system() is waiting for input from its standard input. The system() function will not return until cat 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:

        sprintf(command, "cat < /dev/null > %s", filename);
        system(command);
    

    But if that’s really all you want to do, then it would be more idiomatic to use touch instead of cat:

        sprintf(command, "touch %s", filename);
        system(command);
    
    Login or Signup to reply.
  2. 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:

    FILE *handle = fopen(filename, "w");
    fclose(handle);
    

    If the file already exists, but you want to "empty" it:

    truncate(filename, 0);
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search