Carriage Return in C
What is Carriage Return in C?
“A carriage return is a control character that, when used in C, causes the cursor or print head to jump to the start of the current line rather than the next one. It is symbolised by the escape character "r."”
In typewriters and teleprinters, the carriage would return to the beginning of the queue when this character was used, allowing characters to be written over existing text. These days, updating or overwriting text on the same line on a console or terminal is a standard practise in computers.
Syntax
The C language has a simple syntax for employing the carriage return character, or r. It can be used as a string literal enclosed in double quotes to add a carriage return to the string at that location.
The basic syntax is as outlined below:
("Some text\r");
Because the r is at the end of the string in this example, the cursor will go back to the beginning of the line after printing "Some text," and any additional letters will overwrite what has already been written on the same line.
Example 1
Sure! Let's build another straightforward example in C utilising the carriage return. We'll make a straightforward countdown timer this time that updates on the same line:
#include <stdio.h>
#include <unistd.h>
int main() {
const int countdownStart = 10;
printf("Countdown: ");
for (int i = countdownStart; i >= 0; i--) {
printf("%d", i);
fflush(stdout);
usleep(500000);
printf("\r");
}
printf("\n");
return 0;
}
Output
![Carriage Return in C](https://static.tutorialandexample.com/c/carriage-return-in-c1.png)
Explanation
- The required header files are included, including stdio.h for input/output functions and unistd.h for using the usleep function to add a little delay.
- To specify the initial value for our countdown timer, we define the countdownStart variable.
- The initial "Countdown:" message is printed on the console using printf.
- Our for loop is configured to run from the countdownStart value to 0.
- Printf("%d", i) is used inside the loop to output the current countdown value.
- The output buffer is flushed using fflush(stdout), and the reported value is then shown right away on the terminal. Without this, it's possible that the output won't be displayed until the loop is finished, preventing a visible countdown.
- To simulate a real-time countdown, we add a brief delay of 500 milliseconds using usleep(500000). To alter the countdown pace, change the delay value.
- The previous countdown value is replaced with the new one by using printf("r") to return the cursor to the beginning of the line.
- Up until the countdown reaches zero, the cycle keeps going.
- After the loop, we use printf("n") to print a fresh line and advance the cursor to the following line for further outputs.
The countdown from the supplied value to 0 will appear when you execute this programme, updating on the same line with each value replacing the one before it. By using r to return to the beginning of the queue, together with the delay created by usleep, the appearance of a continuous countdown is created.
Example 2
#include <stdio.h>
#include <unistd.h>
int main() {
const char spinnerChars[] = { '|', '/', '-', '\\' };
const int numSpinnerChars = sizeof(spinnerChars) / sizeof(spinnerChars[0]);
const int totalIterations = 20;
const int delayMs = 100;
printf("Loading: ");
for (int i = 0; i < totalIterations; i++) {
printf("%c", spinnerChars[i % numSpinnerChars]);
fflush(stdout);
usleep(delayMs * 1000);
printf("\r");
}
printf("\n");
return 0;
}
Output
![Carriage Return in C](https://static.tutorialandexample.com/c/carriage-return-in-c2.png)
Explanation
- The required header files are included, including stdio.h for input/output functions and unistd.h for using the usleep function to add a little delay.
- To create a loading spinner animation, we establish an array called spinnerChars that contains characters. These characters, such as "|," "/," "-," and "," stand for the various states of the spinner.
- Using sizeof, we determine how many characters are contained in the spinnerChars array.
- To determine the amount of spinner animation iterations and to configure the millisecond-based delay between animation frames, we declare the constants totalIterations and delayMs.
- The console displays the initial message "Loading:".
- The totalIterations number is iterated through using a for loop.
- Using i% numSpinnerChars, we wrap around to the beginning when we reach the conclusion of the loop and print the current character from the spinnerChars array.
- To flush the output buffer and immediately display the current character on the console, we call fflush(stdout).
- To regulate the animation pace, we use usleep(delayMs * 1000) to impose a brief delay of delayMs milliseconds.
- The spinner animation can be updated continually because printf("r") returns the cursor to the beginning of the line.
- Up till all iterations have been completed, the loop continues.
- After the loop, we use printf("n") to print a fresh line and advance the cursor to the following line for further outputs.
You'll observe a loading spinner motion on the console when you launch this programme. The spinner will repeatedly display the letters '|', '/', '-', and '' to create the illusion that something is loading or being processed in the background.