How can I print a word once a second while using fopen("filename.txt","r")?
I searched earlier and found something that used the unistd.h header file, but in my Turbo C++ no such header file exists.
C++11
If your compiler supports C++11, std::thread::sleep_for is the best, cross-platform solution:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::seconds(1));
// or
using namespace std::chrono_literals;
std::this_thread::sleep_for(1s);
If you are forced to use compiler that doesn't support C++, you have to use platform-specific functions:
POSIX
sleep is part of POSIX.1-2001, so it should run on any compliant operating system, including UNIXes, Linux and Mac OS X:
#include <unistd.h>
sleep(1);
Windows
Sleep is part of WinAPI:
#include <windows.h>
Sleep(1000); // Note capital "S" and that you specify time in milliseconds
Related
I am currently not sure how I should seperate my code best. I currently programming a software which should run on Linux and Windows. So I decided to put all OS-secificstuff in thier own folder/files.
For example
This is the header file:
#ifdef __linux__
#include <unistd.h>
#elif _WIN64
#include <Windows.h>
#endif
#include <string>
#include <iostream>
#pragma once
class SystemTools
{
public:
// Delay in secounds until the programm continues
static void sleep(int delay);
private:
};
and the OS specific implementation is in the linux/windows folder
Linux:
#ifdef __linux__
#include "../SystemTools.h"
void SystemTools::sleep(int delay)
{
usleep(delay*1000000);
}
#endif
Windows:
#ifdef _WIN64
#include "../SystemTools.h"
void SystemTools::sleep(int delay)
{
Sleep(delay*1000);
}
#endif
This works and I have no problems so far, but when I now have methods which don´t need any OS specific code I created an additional folder "Generic" so I can write the code in there and don´t have to mantain the same code in the linux and windows file. For example like that:
Generic:
#include "../SystemTools.h"
void SystemTools::sleepMin(int delay)
{
sleep(delay*60);
}
#endif
That still workes on Linux but not on Windows (no error but does not compile, used codeblockes for that on windows). So how do I organize my code correct? Should I use only one file with ifdef even it that gets very fast ugly?
(compiler Linux: g++, Windows: should be MinGW)
Firstly I'd suggest you to use the most recent of C++ (C++20 or so) on your project. This way, we can abstract many OS related calls (like threading, synchronization, random numbers and etc).
That means, you won't really need to use too many of OS specific APIs. IE: C++11 and earlier already have a standard way to sleep:
https://en.cppreference.com/w/cpp/thread/sleep_for
In the end, if you really need to call OS specific things on windows and on linux, using a library could be interesting and pay attention that windows C++ compiler (visual studio) really like to use 'pre compiled headers' so, it's interesting to have a single header file where all windows specific headers can be included.
Basically that. You can have a standard Cmake or makefile for your linux build and use .sln Visual Studio project to build it to windows.
That's the way I would do that
I am a novice in C++ and I am struggling to make my program to wait a few minutes before executing a function.
I know there are lots of topics about it but I have a problem with my compiler. I can't seem to use the boost library nor the thread library. And since I can't use the thread library, I can't use the chrono library either.
I am using GNU GCC Compiler. I have MinGW installed. Is it outdated or something? What is the best compiler to code in C++?
My OS is Windows.
You could use this
#include <unistd.h>
...
usleep(1000); // Time in microseconds
or
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main(){
int sleepTime = 1000;
Sleep(sleepTime);
return 0;
}
<thread> is only available starting with C++11.
It's likely you don't have the proper flags to tell GCC you want to enable C++11 support, which is disabled by default.
The command line parameter is -std=c++11.
Then, you can use std::this_thread::sleep_for() for cause your program to fall asleep. Note that if you only have one thread in your program, it will probably stop responding to user actions during that time.
I am using dirent.h 1.20 (source) for windows in VC2013.
I can't find mkdir() in it.
How am I supposed to use it? Or can I create a directory somehow only using dirent.h?
simplest way that helped without using any other library is.
#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif
void createDir(string dir) {
#if defined _MSC_VER
_mkdir(dir.data());
#elif defined __GNUC__
mkdir(dir.data(), 0777);
#endif
}
Update: Since C++17, <filesystem> is the portable way to go. For earlier compilers, check out Boost.Filesystem.
The header you are linking to is effectively turning your (POSIX) dirent.h calls into (native) Windows calls. But dirent.h is about directory entries, i.e. reading directories, not creating ones.
If you want to create a directory (mkdir()), you need either:
A similar wrapping header turning your (POSIX) mkdir() call into the corresponding (native) Windows function calls (and I cannot point out such a header for you), or
use the Windows API directly, which might be pragmatic but would lead to a really ugly mix of POSIX and Windows functions...
// UGLY - these two don't belong in the same source...
#include <dirent.h>
#include <windows.h>
// ...
CreateDirectory( "D:\\TestDir", NULL );
// ...
Another solution would be to take a look at Cygwin, which provides a POSIX environment running on Windows, including Bash shell, GCC compiler toolchain, and a complete collection of POSIX headers like dirent.h, sys/stat.h, sys/types.h etc., allowing you to use the POSIX API consistently in your programming.
Visual Studio includes the <direct.h> header.
This header declares _mkdir and _wmkdir, which can be used to create a directory, and are part of the C libraries included with Visual Studio.
The other "easy" option would be to use Windows API calls as indicated by DevSolar.
You can use sys/types.h header file and use
mkdir(const char*) method to create a directory
Following is the sample code
#include<stdio.h>
#include<string.h>
#include <unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int main()
{
if(!mkdir("C:mydir"))
{
printf("File created\n");
}
else
printf("Error\n");
}
mkdir is deprecated. Give #include <direct.h> as a header file. then write
_mkdir("C:/folder")
Where or how can I find the correct C headers to include in a C++ program to obtain the declaration of C functions declared in a POSIX compliant environment?
I'm asking this because I needed to use the open() system call in my C++ program for my purposes, so I initially tried to include the headers mentioned in the online documentation about open() (in the SYNOPSIS section), which are sys/stat.h and fcntl.h. However when trying to compile, the compiler complained that open() was not declared. After a search on google, I found that another possibility was unistd.h. I tried using that header and the program compiled. So I went back to the POSIX documentation to read more about unistd.h to check if open() was mentioned there, but I could not find anything about it.
What am I doing wrong? Why is there this discrepancy between the POSIX documentation and my GCC environment?
On my Linux Debian/Sid, the man 2 open page states:
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
So you need to include all three above files. And open is declared in /usr/include/fcntl.h but needs declaration from the other two includes.
And the following test file
/* file testopen.c */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int
testopen (void)
{
return open ("/dev/null", O_RDONLY);
}
compiles with gcc -Wall -c testopen.c without any warnings.
I have the following source code. Which compiles fine in visual studios and g++ 3.4.6; but not with g++ 4.4.3 (on a newer ubuntu machine). The newer compiler requires that I explicitly include to use atoi. I am just trying to figure out what might have changed to cause this behavior. Is it sstream header file previously included cstdlib and no longer does so. Or is it the compiler behavior that has changed.
#include <sstream>
int main()
{
char str1[]="123";
int i = atoi(str1);
printf ("value = %d",i);
return 0;
}
You also need to include <cstdio> for printf().
Technically, if you include the headers of the form <cname> instead of <name.h>, you also need to qualify the names from the standard library using std::. A lot of standard library implementations are relaxed when it comes to this, though, and also put the names into the global namespace.
It's implementation-dependent which headers are included by which other headers, so you should always be sure to include all the headers that you need and not assume that they will be included automatically.
I'm using GCC 4.4.5 on Debian, and the headers have changed so you will not bring in the headers necessary. You need to #include <cstdlib> and #include <cstdio> to get atoi and printf, as the compiler complained about both being missing.
#include <sstream>
#include <cstdio>
#include <cstdlib>
int main()
{
char str1[]="123";
int i = std::atoi(str1);
std::printf ("value = %d",i);
return 0;
}
Well yes. That is common. You should always include ALL headers that you are directly using and not depend on the fact that those headers are already included.
Compiler behavior is what would have changed... the <sstream> doesn't use atoi.
Arguably you should have always done #include <cstdlib>, and you'd gotten lucky with your previous compilers.
As James McNeillis points out, you should also #include <cstdio> in order to use the printf function.