Libraries "X11/Xlib.h", "X11/Xutil.h", "unistd.h" for Windows - c

I've done a C program that takes the RGB values (0-255) of a pixel of the screen knowing its position (x,y). It works in Linux, but when I try to compile it in Visual Studio (Windows), crashes because libraries X11/Xlib.h, X11/Xutil.h, unistd.h doesn't exist.
This is the code:
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void getimage(XColor c, Display* d, int* rgb, int x, int y) {
XImage* image;
image = XGetImage(d, RootWindow(d, DefaultScreen(d)),
x, y, 1, 1, AllPlanes, XYPixmap);
c.pixel = XGetPixel(image, 0, 0);
XFree(image);
XQueryColor(d, DefaultColormap(d, DefaultScreen(d)), &c);
rgb[0] = c.red / 256;
rgb[1] = c.green / 256;
rgb[2] = c.blue / 256;
}
int main () {
int rgb[3], x, y;
XColor c;
Display* d = XOpenDisplay((char*)NULL);
getimage(c, d, rgb, x, y);
}
How can I implement this to run in Windows?

You've written an X11 program. X is the consensus standard for graphical displays on UNIX-like systems other than OS X (but it is also freely available for OS X).
Windows uses a completely different graphical display API. It is conceivable that you could find an X implementation that runs on Windows, but Microsoft certainly doesn't provide one. Since your program is quite short, your best bet is probably to rewrite it using the Windows API.
As for unistd.h (and time.h), I don't see anything in your program that depends on it. If you weren't going to rewrite the program, you could resolve that part of your problem simply by removing the offending #include statement.

One small part to the answer for your question may be to search around MSDN. The following function is described there: (link below)
#include <Windows.h>
...
DWORD WINAPI GetSysColor(
_In_ int nIndex
);
To use that function, you must link to User32.lib which is implemented in User32.dll
The descriptions of GetSysColor(...) et. al. are accessible here. This function is one of many that support similar functionality, but warning, the usage methods will be like a completely different language. Windows programming is rarely similar to Linux programming.
Other starting points to Windows related graphical/image programming:
capturing an image
Create your own Snipping tool

Related

How to color output in C for cross-platform app

I am new and I know how to color output only in Unix/Linux systems:
#include <stdio.h>
int main(void) {
printf("\033[1;31mRed Message\033[0m.");
}
But this is not works in Windows cmd.exe, only in Unix terminal.
I am writing cross-platform app and want to know how can I do this in Windows cmd.exe too.
This also does not works:
1.
#include <stdio.h>
int main(void) {
printf("%c[1;31mRed Message%c[0m", 27, 27);
}
2.
#include <stdio.h>
int main(void) {
printf("[1;31m Red Message [0m");
}
This works, but I think this is just a bug:
If I type system(""); before printf then it works.
#include <stdio.h>
int main(void) {
system("");
printf("\033[1;31m Red Message \033[0m");
}
Thanks
If you want to make your library crossplatform, I would use the following approach:
Have a library, with the same functions, let's say:
void printInRed(const char* string). (In a headerfile)
After that you write two or more implementations.
One for windows:
//TODO: Errorchecking
void printInRed(const char* string){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
//TODO: Extract magic number
//See https://stackoverflow.com/a/4053879/13912132
SetConsoleTextAttribute(hConsole, 12);
puts(string);
}
And another one for unix-like OS:
//TODO: Errorchecking
void printInRed(const char* string){
printf("\033[1;31m%s\033[0m.", string);
}
Then you can check at compile time, which version to compile.
The first approach is to use #ifdefs, but this will make the code a bit messy.
Another approach would be to use a build-system like CMake to select at build time, which one to build. A buildsystem requires a bit of learning, but will help you to make maintaining a crossplatform library simpler.

What function clears the screen on a mac terminal?

I'm new to C and I do not own a mac, but I'm working on a personal project for someone who does and part of the project's requirements is that it clears the screen. The reason I need to clear the screen is that it's part of a loop that clears the screen and then prints something again (I'm trying to make a "ticking counter" of sorts.)
I know that system("cls") works well on my terminal (obviously any system function isn't ideal though), however, I know that she's on a Mac OS, and that the system() function is notoriously nonportable and I need this to work on a mac. I've scoured the internet trying to see what system functions clear the screen on a mac, and the most recent source I could find was from 2006. Considering how often the mac gets updated, I'm not surprised that
I don't really need a solution that's elegant or secure, just an idea for something that works. My compiler is MinGW with GCC for libraries.
Here's a sample of the relevant code:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main()
{
time_t seconds; //variable declarations
float days;
float rate;
int i;
i = 3;
char str[50];
while (i > 2);
{
time(&seconds);
days = (seconds - ((float)1584673594)) / (float)86400;
rate = pow(1.05, days);
rate = rate * 100;
printf("\nCurrent Snuggle-Debt Balance: %f snuggles\n", rate);
printf("Days passed: %f \n", days);
sleep(.5);
system("cls");
If you're writing a C program that uses standard input and output, and you need to do things like move the cursor around or clear part or all of the screen, the curses library is what you want. Curses is widely available and does what you want and much more. To clear the screen, just call the clear() function. And that's just the beginning of what you can do.

Get program's directory on windows [duplicate]

Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
Here's code to get the full path to the executing app:
Variable declarations:
char pBuf[256];
size_t len = sizeof(pBuf);
Windows:
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;
If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from the directory that holds the current executable program file. It isn't necessarily the same directory; if someone runs the program from a command prompt, then the program is being run from the command prompt's current working directory even though the program file lives elsewhere.
getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).
Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.
On windows getcwd function has been deprecated in favour of _getcwd. I think you could use it in this fashion.
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf ("The current working directory is %s", cCurrentPath);
This is from the cplusplus forum
On windows:
#include <string>
#include <windows.h>
std::string getexepath()
{
char result[ MAX_PATH ];
return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
}
On Linux:
#include <string>
#include <limits.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
return std::string( result, (count > 0) ? count : 0 );
}
On HP-UX:
#include <string>
#include <limits.h>
#define _PSTAT64
#include <sys/pstat.h>
#include <sys/types.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
struct pst_status ps;
if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)
return std::string();
if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)
return std::string();
return std::string( result );
}
If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.
If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost's filesystem library and ask for the initial_path().
IMHO that's as close as you can get, with good karma (Boost is a well-established high quality set of libraries)
I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:
int main(int argc, char* argv[])
{
std::string argv_str(argv[0]);
std::string base = argv_str.substr(0, argv_str.find_last_of("/"));
}
You can now just use this as a base for your relative path. So for example I have this directory structure:
main
----> test
----> src
----> bin
and I want to compile my source code to bin and write a log to test I can just add this line to my code.
std::string pathToWrite = base + "/../test/test.log";
I have tried this approach on Linux using full path, alias etc. and it works just fine.
NOTE:
If you are on windows you should use a '\' as the file separator not '/'. You will have to escape this too for example:
std::string base = argv[0].substr(0, argv[0].find_last_of("\\"));
I think this should work but haven't tested, so comment would be appreciated if it works or a fix if not.
Filesystem TS is now a standard ( and supported by gcc 5.3+ and clang 3.9+ ), so you can use current_path() function from it:
std::string path = std::experimental::filesystem::current_path();
In gcc (5.3+) to include Filesystem you need to use:
#include <experimental/filesystem>
and link your code with -lstdc++fs flag.
If you want to use Filesystem with Microsoft Visual Studio, then read this.
No, there's no standard way. I believe that the C/C++ standards don't even consider the existence of directories (or other file system organizations).
On Windows the GetModuleFileName() will return the full path to the executable file of the current process when the hModule parameter is set to NULL. I can't help with Linux.
Also you should clarify whether you want the current directory or the directory that the program image/executable resides. As it stands your question is a little ambiguous on this point.
On Windows the simplest way is to use the _get_pgmptr function in stdlib.h to get a pointer to a string which represents the absolute path to the executable, including the executables name.
char* path;
_get_pgmptr(&path);
printf(path); // Example output: C:/Projects/Hello/World.exe
Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.
For example:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
char the_path[256];
getcwd(the_path, 255);
strcat(the_path, "/");
strcat(the_path, argv[0]);
printf("%s\n", the_path);
return 0;
}
When run, it outputs:
jeremy#jeremy-desktop:~/Desktop$ ./test
/home/jeremy/Desktop/./test
For Win32 GetCurrentDirectory should do the trick.
You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily - process could be created with arbitrary value in the field.
Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won't help you either.
On Windows use GetModuleFileName(), on Linux read /dev/proc/procID/.. files.
Just my two cents, but doesn't the following code portably work in C++17?
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}
Seems to work for me on Linux at least.
Based on the previous idea, I now have:
std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");
With implementation:
fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
static auto exe_parent_path = fs::path(exe_path).parent_path();
return exe_parent_path / filename;
}
And initialization trick in main():
(void) prepend_exe_path("", argv[0]);
Thanks #Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.
Just to belatedly pile on here,...
there is no standard solution, because the languages are agnostic of underlying file systems, so as others have said, the concept of a directory based file system is outside the scope of the c / c++ languages.
on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is - ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.
#include <windows.h>
using namespace std;
// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
const unsigned long maxDir = 260;
char currentDir[maxDir];
GetCurrentDirectory(maxDir, currentDir);
return string(currentDir);
}
For Windows system at console you can use system(dir) command. And console gives you information about directory and etc. Read about the dir command at cmd. But for Unix-like systems, I don't know... If this command is run, read bash command. ls does not display directory...
Example:
int main()
{
system("dir");
system("pause"); //this wait for Enter-key-press;
return 0;
}
Works with starting from C++11, using experimental filesystem, and C++14-C++17 as well using official filesystem.
application.h:
#pragma once
//
// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
//
#ifdef __cpp_lib_filesystem
#include <filesystem>
#else
#include <experimental/filesystem>
namespace std {
namespace filesystem = experimental::filesystem;
}
#endif
std::filesystem::path getexepath();
application.cpp:
#include "application.h"
#ifdef _WIN32
#include <windows.h> //GetModuleFileNameW
#else
#include <limits.h>
#include <unistd.h> //readlink
#endif
std::filesystem::path getexepath()
{
#ifdef _WIN32
wchar_t path[MAX_PATH] = { 0 };
GetModuleFileNameW(NULL, path, MAX_PATH);
return path;
#else
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
return std::string(result, (count > 0) ? count : 0);
#endif
}
For relative paths, here's what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:
Say you have a path like this:
"path/to/file/folder"
For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!
As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:
"./path/to/file/folder"
Just adding "./" should get you sorted! :) Then you can start loading from whatever directory you wish, so long as it is with the executable itself.
EDIT: This won't work if you try to launch the executable from code::blocks if that's the development environment being used, as for some reason, code::blocks doesn't load stuff right... :D
EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):
"resources/Example.data"
If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that.
Keep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)
A library solution (although I know this was not asked for).
If you happen to use Qt:
QCoreApplication::applicationDirPath()
Path to the current .exe
#include <Windows.h>
std::wstring getexepathW()
{
wchar_t result[MAX_PATH];
return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));
}
std::wcout << getexepathW() << std::endl;
// -------- OR --------
std::string getexepathA()
{
char result[MAX_PATH];
return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));
}
std::cout << getexepathA() << std::endl;
On POSIX platforms, you can use getcwd().
On Windows, you may use _getcwd(), as use of getcwd() has been deprecated.
For standard libraries, if Boost were standard enough for you, I would have suggested Boost::filesystem, but they seem to have removed path normalization from the proposal. You may have to wait until TR2 becomes readily available for a fully standard solution.
Boost Filesystem's initial_path() behaves like POSIX's getcwd(), and neither does what you want by itself, but appending argv[0] to either of them should do it.
You may note that the result is not always pretty--you may get things like /foo/bar/../../baz/a.out or /foo/bar//baz/a.out, but I believe that it always results in a valid path which names the executable (note that consecutive slashes in a path are collapsed to one).
I previously wrote a solution using envp (the third argument to main() which worked on Linux but didn't seem workable on Windows, so I'm essentially recommending the same solution as someone else did previously, but with the additional explanation of why it is actually correct even if the results are not pretty.
As Minok mentioned, there is no such functionality specified ini C standard or C++ standard. This is considered to be purely OS-specific feature and it is specified in POSIX standard, for example.
Thorsten79 has given good suggestion, it is Boost.Filesystem library. However, it may be inconvenient in case you don't want to have any link-time dependencies in binary form for your program.
A good alternative I would recommend is collection of 100% headers-only STLSoft C++ Libraries Matthew Wilson (author of must-read books about C++). There is portable facade PlatformSTL gives access to system-specific API: WinSTL for Windows and UnixSTL on Unix, so it is portable solution. All the system-specific elements are specified with use of traits and policies, so it is extensible framework. There is filesystem library provided, of course.
The linux bash command
which progname will report a path to program.
Even if one could issue the which command from within your program and direct the output to a tmp file and the program
subsequently reads that tmp file, it will not tell you if that program is the one executing. It only tells you where a program having that name is located.
What is required is to obtain your process id number, and to parse out the path to the name
In my program I want to know if the program was
executed from the user's bin directory or from another in the path
or from /usr/bin. /usr/bin would contain the supported version.
My feeling is that in Linux there is the one solution that is portable.
Use realpath() in stdlib.h like this:
char *working_dir_path = realpath(".", NULL);
The following worked well for me on macOS 10.15.7
brew install boost
main.cpp
#include <iostream>
#include <boost/filesystem.hpp>
int main(int argc, char* argv[]){
boost::filesystem::path p{argv[0]};
p = absolute(p).parent_path();
std::cout << p << std::endl;
return 0;
}
Compiling
g++ -Wall -std=c++11 -l boost_filesystem main.cpp
This question was asked 15 years ago, so the existing answers are now incorrect. If you're using C++17 or greater, the solution is very straightforward today:
#include <filesystem>
std::cout << std::filesystem::current_path();
See cppreference.com for more information.

R CMD SHLIB to create a DLL from a source .c file which needs an external library (on Windows x64)

First things first, I am very new to C programming and the whole idea of compilation, so I would really appreciate some very straightforward and step-by-step guidance on this.
Here is my problem: I am trying to write some C code that I can dyn.load into R to speed up my R task. My C code would involve some very complex matrix operation that is only available in an external library with the header file "matrix.h" and the static library file "matrix.lib". It would also make use of some basic R header files such as "Rdefines.h", etc. The files "matrix.h" and "matrix.lib" are located at C:\lcc\include and C:\lcc\lib, respectively. Here is a sample test C code:
#include <Rmath.h>
#include <R.h>
#include <Rdefines.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <matrix.h>
void foo(double *cdegree, double *fdegree, int *size) {
int i;
for(i=0; i<*size; i++) {
cdegree[i] = 5.0/9.0*(fdegree[i]-32.0);
}
}
As you can see, this is simple code converting Fahrenheit to Celsius. Although the test code does not make use of anything in the matrix library, the goal here is to be able to include both the R header files and matrix.h from the external library. If I try R CMD SHLIB this C code I get the "no such file or directory" error for trying to include "matrix.h". How can I tell R to compile this with the external library? Everything is done on a Windows 8.1 X64 system.
Honestly, you will find it much easier if you start exploring Rcpp. Here is a link to introduce you to Rcpp. There are many examples to be found throughout the documentation.
f2c.cpp
#include <Rcpp.h>
// [[Rcpp::export]]
void foo(Rcpp::NumericVector fdegree, Rcpp::NumericVector cdegree, int size){
int i;
for(i=0; i < size; i++){
cdegree[i] = 5.0/9.0*(fdegree[i]-32.0);
}
}
R code
library(Rcpp)
sourceCpp("f2c.cpp")
fdegree <- c(98.6, 212, 32)
cdegree <- c(0,0,0)
foo(fdegree, cdegree, length(fdegree))
cdegree
[1] 37 100 0
Naturally this makes some assumptions but it demonstrates how you can quickly use some C code and not fiddle with all the R headers and SHLIB.
Regarding your concern to use some external headers, just simply set the PKG_CXXFLAGS environmental variable to the location of your header(s).
Sys.setenv("PKG_CXXFLAGS" = '-I"path/to/headers"')
followed by the same compilation.
sourceCpp("f2c.cpp")
However, it should be noted that if you are doing more than a few of these functions you should build a package with Rcpp and provide an appropriate Makevars file. You can find further information on Rcpp package development here.

How do I properly allocate a memory buffer to apply double buffering in dosbox using turbo c?

Okay so I am trying to apply a double buffering technique in an emulated environment (DosBox) while using the IDE Turbo C++ 3.0 I am running windows 7 64bit(Not sure if that matters) and I have no clue how to properly execute the buffering routine in this environment.
The main problem I am having is that I can't seem to execute the following assignment statement:
double_buffer = (byte_t far*)farmalloc((unsigned long)320*200);
(Note that 320 and 200 are the screen sizes)...
I just get NULL for the assignment.
I tried changing the default RAM usage of the DosBox to 32 instead of 16, but that didn't do anything. I'm not sure if it's the emulator or there is something wrong with the code for Turbo C. (Note that it complies just fine).
Here is a sample program I found online:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <dos.h>
#include <string.h>
#include <alloc.h>
typedef unsigned char byte_t;
byte_t far* video_buffer = (byte_t far*)0xA0000000;
void vid_mode(byte_t mode){
union REGS regs;
regs.h.ah = 0;
regs.h.al = mode;
int86(0x10,&regs,&regs);
}
void blit(byte_t far* what){
_fmemcpy(video_buffer,what,320*200);
}
int main(){
int x,y;
byte_t far* double_buffer;
double_buffer = (byte_t far*)farmalloc((unsigned long)320*200);
if(double_buffer == NULL){
printf("sorry, not enough memory.\n");
return 1;
}
_fmemset(double_buffer,0,(unsigned long)320*200);
vid_mode(0x13);
while(!kbhit()){
x = rand()%320;
y = rand()%200;
double_buffer[y * 320 + x] = (byte_t)(rand()%256);
blit(double_buffer);
}
vid_mode(0x03);
farfree(double_buffer);
return 0;
}
Your problem is related to running your application within the Turbo-C IDE debugger. If you compile it and then exit the IDE and run it directly from the DosBox command line without the IDE it should work as expected.
When running via the IDE, the default debug option is to only allocate an additional 64KiB memory for your program's heap. This isn't enough to handle your request for the 64000 bytes (320*200). In the Turbo-C IDE pull down the options menu, click on debugger. You should get a screen that looks like this:
The default value for Program Heap Size is 64. Change it to the maximum 640 and then click Ok. Rerun your program and it should display randomly colored pixels on the display at random locations.

Resources