Printf statement executed after system command - c

I have this simple program written and executed on wsl2.
#include<stdio.h>
int main(){
printf("Current date is : ");
system("date");
printf("\n");
return 0;
}
For some reason, the printf statement is getting executed last. So here is the output I am getting.
Mon Nov 7 12:00:49 IST 2022
Current date is :
Any idea how I can handle the sequence of execution?
My expectation is for printf to execute first.

Related

Difference in output between Command Prompt looking terminal and VSC Terminal

I recently started learning C and have just started using VSC. I was previously using CodeBlocks. While testing out a simple array program, I realised that there is a difference in output. For reference, the array program code is shown below.
#include <stdio.h>
int main() {
int grades[10];
int count = 10;
long sum;
float average;
printf("\nPlease enter the 10 grades: \n");
//printf("%i", count);
for(int i = 0; i < count; i++) {
printf("%2u> ", i+1);
scanf("%d", &grades[i]);
sum += grades[i];
};
average = (float)sum/count;
printf("The average of the 10 grades are %.2f", average);
return 0;
}
I am able to run the for loop but the code after the for loop does not appear in the CMD like terminal and the program just quits after the for loop. However, the code after the for loop does appear in the VSC terminal. I am able to enter the ten values.
The VSC Terminal Output:
However, the CMD looking terminal did not manage to print the code after the for loop and instead exits the program.
Could it be because of this error: "The preLaunchTask 'C/C++:gcc.exe build active file' terminated with exit code -1." everytime I click 'Run > Start Debugging'.
Sorry for this messy format but thank you in advance for helping!

String buffer overflow produced by asctime() in C

I want to print out the time in C using asctime(), but when the text gets printed out random charaters are appended after timeString. Also, the text syslog() prints out in the log file differs from the text printed in the shell by printf(). Under the code I've provided the exact output from both outputs. How do I get rid of this behavior? The code is running on a RaspberryPi and I'm logged in via the default macOS terminal.
time_t rawTime;
time(&rawTime);
struct tm timeInfo = *gmtime(&rawTime);
// ...
char *log;
char *timeString = strdup(asctime(&timeInfo));
asprintf(&log, "UTC: %s %.*s Last status: %s. New status: %s.",
timeString, 5, " ", "Hello", "World");
openlog("httpd-status-notifier", LOG_PID, LOG_USER);
syslog(logLevel, "%s", log);
printf("%s\n", log);
// ...
Syslog:
Dec 22 17:18:17 rasp httpd-status-notifier[25458]: UTC: Sun Dec 22 17:18:17 2019#012 Last status: Hello. New status: World.
(Here syslog produces #012)
Shell (printf):
UTC: Sun Dec 22 17:18:17 2019
Last status: Hello. New status: World.
(Here printf produces a new line charater)
Btw., yes I did notice that syslog already logs the date.
The problem is that asctime() produces a new line character and this gets represented as the octal ASCII value 012 in the log file as pointed out by #mangusta in the comment section. So trimming the string solves the problem.

Leap year question, unable to get input or .exe crashes

sorry, might be really dumb just started to learn C.
it's a basic check if the input year is a leap year or not.
I don't understand where I am going wrong. the executable starts but as soon as I input a year and press enter it closes.
I tried to remove the return 0; by using void main instead cause I thought it is causing the abrupt crash. I don't know enough to try anything else.
#include <stdio.h>
int main() {
int year;
printf("Enter year below\n");
scanf("%d", &year);
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
printf("%d is a Leap year", year);
else
printf("%d is not a Leap year", year);
} else
printf("%d is a Leap year", year);
} else
printf("%d is not a Leap year", year);
return 0;
}
I expected it to be able to check the leap year but it just crashes.
Your are running a console program in Windows directly from the IDE. Windows opens a terminal window for the duration of the program and closes it immediately upon program termination.
This problem has been plaguing students trying to lean C on this legacy system for 25 years. Microsoft seems to be unwilling to fix this issue, either in the terminal or in the IDE. Truth is they do not encourage C programming at all, but the same problem occurs for other languages too.
You can force the program to wait for extra input before terminating, so you can see its output. Yet you must read more than one extra character as scanf() will have left the newline produced by the key pending in the standard input.
Here is a modified version that should work:
#include <stdio.h>
int main() {
int year;
printf("Enter year below\n");
if (scanf("%d", &year) != 1) {
printf("invalid input\n");
} else {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
printf("%d is a Leap year\n", year);
else
printf("%d is not a Leap year\n", year);
} else {
printf("%d is a Leap year\n", year);
}
} else {
printf("%d is not a Leap year\n", year);
}
}
getchar(); /* read the pending newline */
getchar(); /* read extra input to keep the terminal window open */
return 0;
}
As chux commented, the algorithm implements the rules for the Gregorian Calendar established by pope Gregory XIII in 1582, and adopted progressively at different times across the world. Using this method for years before 1582 seems incorrect from a historical perspective, but is actually quite common and useful. It is known as the Proleptic Gregorian Calendar.
It should be scanf("%d", &year); instead of scanf("%d", year);. scanf requires the address of the variable to write into. Your compiler should have warned you about that.
If you're directly running the .exe from Windows, it'll automatically close because once the application finishes, Windows closes the window. You can run it from the command prompt or put something at the end of your code to hold the session open (like getchar()).

File modified time result does not match up with current time

I am working on a program in which I need to compare the time of which a file was modified to the current time. If a file has not been modified for a certain amount of time, then it is considered "old" and a process is killed.
However, when I get my current time and my modification time they do not return comparable results. They appear to come back in the same format, but the difference between the two doesn't make sense. I am assuming that this has something to do with the timezone or perhaps how I am returning the times. Tried doing some searching but haven't been able to find anything that has fixed my issue.
Get modified time:
time_t getMod(const char *file){
struct stat attrib;
if (stat(file, &attrib) == -1) {
perror(file);
exit(1);
}
return attrib.st_mtime;
}
Get current time and compare:
while(loop == 1){
printf ("Sleeping..\n");
sleep(numSleep); //Sleep
printf ("Awake..\n");
curTime = time(0); //Current time
modTime = getMod(argv[fileIndex]); //Modified time
printf ("Current time: %d\n", curTime);
printf ("Modified time: %d\n", modTime);
seconds = curTime - modTime;
printf ("Seconds: %d\n", seconds);
if(seconds > numSleep){
kill(pid, SIGKILL);
}
}
An example of the output I have been getting when I modify the file while sleep:
Current time: 1433371851
Modified time: 1433374890
This almost certainly has to be a file stored on a different server. The st_mtime field is updated by the server using the server's clock even if the file was modified remotely from a client machine. When the clocks differ on the client and server, this can lead to apparent discrepencies for modification times.
Either the server or the host where you are running the program has the clock set wrong.
The values returned either by time() or stat should be irrespective of timezones as they should be the standard linux Epoch (which is the number of seconds since 00:00:00 UTC Jan 1 1970 -with some minor caveats) So differences in timezone settings shouldn't account for it.
You can do a simple test from the host where you are running the program while you are in the same directory that you are using now:
echo x > file; ls -l file; date
The times reported by ls and date should very closely agree. If not, the clock is set wrong on the client or server.

calling system() from c

I was trying to execute system calls from c. When the following code is executed, the date is printed first followed by " Todays date is ..........:" on a new line. When I replaced printf by puts, it executed as I intended.(the objdump showed puts#plt in place of the second printf). Can anybody tell me why it is so?
#include <stdlib.h>
int main() { printf(" Todays date is ..........:");
system("/bin/date");
printf("\n This is your exclusive shell\n");
system("/bin/sh");
return 0;
}
Thanks in advance.
The printf() put your string in a buffer, and once you go down a line it write it to the screen. that's why when you do
printf(" Todays date is ..........:");
system("/bin/date");
You might get the date printed first.
The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:
Print to stderr instead using fprintf:
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush:
printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer
or you can also disable buffering on stdout by using setbuf:
setbuf(stdout, NULL);
printf(" Todays date is ..........:");
==>
printf(" Todays date is ..........:\n");
Or add a fflush(stdout); after the printf line;
printf use a buffer.
If you want to print the text immediately you have to call fflush
printf(" Todays date is ..........:");
fflush(stdout);
system("/bin/date");
#include <stdlib.h>
#include <stdio.h>
int main() { printf(" Todays date is ..........:\n"); //add \n at the end. this is same behavior as puts. now date will print after this
system("/bin/date");
printf("\n This is your exclusive shell\n");
system("/bin/sh");
return 0;
}
or else you can use fflush(stdout); after printf("Todays date is ....:"); statement

Resources