Are system () C functions normal?

I am writing a C program containing an OO page. I thought that when the user wants to read this page, the console will clear (for example, if I execute the clear command in linux bash) and show the contents of the page. After a little look, I found this solution:

system("clear"); 

This is normal? I mean, is it safe to use in a program? What are the advantages and disadvantages?

+8
c
source share
3 answers

In a sense, that system is part of the C standard library, the function itself is completely safe. The problem is the command part of the call, i.e. "clear" in your example. It depends a lot on the system, which makes your program not portable.

A common solution to this problem is to provide commands separately from your program (for example, in a file) or to define them in part of your code, which is conditionally compiled. The first solution is a little more flexible, but the second solution is easier to implement.

How could I implement a solution that would execute system("clear") for Linux Terminal and system("cls") for Windows Terminal?

The conditional compilation approach will look like this: first, put these definitions in your program

 #ifdef WIN_TERMINAL #define CLEAR_COMMAND "cls" #endif #ifdef UNIX_TERMINAL #define CLEAR_COMMAND "clear" #endif 

Now use this command in your code:

 system(CLEAR_COMMAND); 

When compiling on UNIX, pass -D UNIX_TERMINAL when compiling your program. This is usually included in your Makefile . On Windows, pass /D WIN_TERMINAL compiler. This usually happens in the flag list of the preprocessor of your Visual Studio project.

+9
source share

Advantage: This is a quick, well-defined method, because there is no other “predefined function” for this.

Disadvantage: OS dependent. On Windows, you will need to use system("cls") .

+2
source share

There are serious flaws when running a command through the system. Firstly, there are security implications and platform differences.

Ideally, you should print platform escape sequences to get the desired result or interface with the platform API. This will reduce the dependencies that exist in cls / clear commands and also prevent unwanted results if these commands are not standard.

0
source share

All Articles