I was trying to write a program that checks out if a location exists under the /home/user directory. To do that, I had to get the username with the whoami
command and add the output of it to the buffer to use the locate
command.
However, even though the snprintf
read the whoami
command, it didn't read the rest. I made a couple of searches and came to a result that NULL
may not be terminated at the end of the string. Nevertheless, I couldn't find out how to terminate it manually. I am not sure what the problem is, so, here I am.
Here is the code for a better demonstration of my issue:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
char *readFile(char *);
bool check();
bool check() {
char path[200] = { 0 };
snprintf(path, 200, "/home/%s/.example", readFile("whoami"));
char lll[300] = { 0 };
snprintf(lll, 300, "locate %s", path);
char *buffer = readFile(lll);
if (strcmp(buffer, path) == 0) {
return true;
} else {
return false;
}
}
char *readFile(char cmd[200]) {
char cmd1[99999] = { 0 };
system("touch cmd");
snprintf(cmd1, 99999, "%s >> cmd", cmd);
system(cmd1);
FILE *f = fopen("cmd", "rt");
assert(f);
fseek(f, 0, SEEK_END);
long length = ftell(f);
fseek(f, 0, SEEK_SET);
char *buffer = (char *)malloc(length + 1);
buffer[length] = '\0';
fread(buffer, 1, length, f);
fclose(f);
system("rm cmd");
return buffer;
}
int main() {
int x = check();
if (x == 1)
printf("There is a location like that");
else
printf("There isn't");
return 0;
}