Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
./report.txt
Jason Isom said:Does C not have that requirement? Will "." always resolve to the directory the executable lies in?
This isn't true on Windows. If FOO.EXE is in C:\FOO, and I've got the shell open on D:\BAR, issuing the command "C:\FOO\FOO.EXE" will runn FOO.EXE with the current working directory of D:\BAR.doh said:Unless chdir(2) was issued.
mikeblas said:"I want to use the current directory" is a different question than "I want to use the same directory as the location of the program's executable".
#include <cstdio>
#include <string>
using namespace std;
// Use argv[0] to generate an absolute (if necessary) path to a file in the directory of this exe
// Works on *nix also
string generatePath(const string& s, const string& file) {
if (s.find("/") != string::npos) {
return s.substr(0, s.rfind( "/" )) + "/" + file;
} else if (s.find("\\") != string::npos) {
return s.substr(0, s.rfind("\\")) + "\\" + file;
} else {
return file;
}
}
int main(int, char* argv[]) {
const string file = generatePath(argv[0], "file.txt");
printf("%s\n", file.c_str());
}
// g++ -Wall -Wextra -ansi -pedantic this.cpp -o this -O3 -s
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void subcpy(char* target, const char* const src, const char* const stop) {
size_t i = 0;
while(&src[i] != stop) {
target[i] = src[i];
++i;
}
target[i] = 0;
}
char* generatePath(const char* const arg0, const char* const file) {
char* p = (char*)malloc(sizeof(char) * (strlen(arg0) + strlen(file) + 2 ));
if (!p) {
exit(1);
}
if (strchr(arg0, '/')) {
subcpy(p, arg0, strrchr(arg0, '/') + 1);
strcat(p, file);
} else if (strchr(arg0, '\\')) {
subcpy(p, arg0, strrchr(arg0, '\\') + 1);
strcat(p, file);
} else {
strcpy(p, file);
}
return p;
}
int main(int argc, char* argv[]) {
char* path;
if (!argc) { /* get rid of unused argc warning */
return 1;
}
path = generatePath(argv[0], "file.txt");
printf("%s\n", path);
free(path);
return 0;
}
/* gcc - Wall -Wextra -ansi -pedantic this.c -o this -O3 -s */