c programming how to convert system output to char [duplicate] - c

This question already has answers here:
How do I execute a command and get the output of the command within C++ using POSIX?
(12 answers)
Closed 7 years ago.
I was wondering if anyone can help me:
I need to turn the output of the system command : whoami into a variable.
Example:
char *a;
a = system("whoami");
printf("username = %s",a);
I have tried a few methods such as printing the commands output to a text file like: whoami >> output.txt and than making the program read from that file, however i am encountering errors through that method. I also consider that method to be a little messy and unnecessary as im positive that there must be a way within C to let me do this.
This question may be a duplicate so please label as necessary(but also answer if capable)
Thanks a lot :)

If everything you want is to read an environment variable in a POSIX environment, you can simply call getenv:
http://man7.org/linux/man-pages/man3/getenv.3.html
#include <stdlib.h>
#include <stdio.h>
int main() {
char* username = getenv("USER");
printf("username = %s\n", username);
return 0;
}
If you want something more complex, you can use popen:
http://man7.org/linux/man-pages/man3/popen.3.html to create a pipe to a process and read from stdout, this answer should help in that case:
C: Run a System Command and Get Output?

This should do the trick. I haven't tested it myself, but I checked and its listed in the Linux man pages so I'm sure its kosher.

Related

How can I fix my problem with colored output in C [duplicate]

This question already has answers here:
How to make win32 console recognize ANSI/VT100 escape sequences?
(14 answers)
Closed 2 years ago.
I want to print a colored sentence,
My code:
#include<stdio.h>
int main()
{
printf("\033[0;34m");
printf("This is Blue");
return 0;
}
And this is output:
[0;34mThis is Blue
How can I fix this problem?
Your program does exactly what it is supposed to do: output what you tell it to to the console.
However, if you are expecting to see colors when sending ANSI/VT100 codes to the console the console must understand these codes.
You didn't mention what operating system and console you are using.
If it's Windows for example the console doesn't support ANSI/VT100 codes by default (to enable see: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences?redirectedfrom=MSDN).
If it Unix or Linux you may need to check what the TERM environment variable is set to and if that is supported by the console application you're using.
If you are using a remote console (like PuTTY on Windows) you may need to set the terminal type to xterm-color.

How to use bin2h?

I'm trying to use bin2h to convert a font file (font.ttf) into a C file but it won't work.
Can someone please tell me the syntax to save the output to a text file?
I've been trying to figure this out but nothing is working, and it's driving me insane. I'm really frustrated because I know the tool is working (I got it to work like a year ago) but I can't remember how I used it.
The example syntax on that site doesn't really help...
Please
Thanks to Lightness Races in Orbit's comment below I finally got the syntax right!
bin2h -cz font < font.ttf > output.h
That's working, thanks
Perhaps you are looking at the usage example on the website and not realising that it is a program that you execute from shell? It is not a line of C code.
So if you want to use this from a C program, you will need to execute it through a function like system or exec. However, since its output is a line of C code, you'd be better off running it from within your build script to create a C script, that you'd then link in to the rest of your program.
Example (in C++ as my C is rusty — port to C as required):
Source code for main.cpp
#include <iostream>
#include "eula.h"
int main()
{
std::cout << std::string(eula, eula_size) << std::endl;
}
Build commands
$ bin2h -cz eula < eula.txt > eula.h
$ g++ main.cpp -o myProgram
Execution command
$ ./myProgram
I would just write my own.
Here's the algorithm:
Open the source code file as text output.
Open the font file as binary input.
Write the array declaration to the output file, something like:
static const unsigned char font[] =
{
While the font file is not empty do:
Read unsigned char from font file, using binary read methods.
Output the unsigned char, in text format, to the source file.
end-while
Write the ending brace and semicolon to the source file.

Deleting a file using a FILE * [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I delete a file pointed to by a FILE* in C?
I want to delete a file at the end of a C program, by which point the filename has been long forgotten. It would be nice if I could just use the FILE * to delete it directly or find the filename and then use remove()... rather than having to memorize the filename for this.
Does anybody know of any ways in which this could be achieved? I am on a Windows system, but I need to maintain portability so can't use any OS specific stuff.
nice if I could just use the FILE * to delete it directly or find the
filename and then use remove()... rather than having to memorize the
filename for this
There's no way to retrieve the file name from a FILE *. A FILE * isn't necessarily a real file; just think of popen(3) for example.
I do not know of a portable way, but there is a Linux version (which might work on other unices) and a Windows version:
Linux: a readlink() on sprintf("/proc/self/fd/%d",fd) should work
Windows: GetFileInformationByHandleEx() will give you the name as part of a struct (Search MSDN, don't have the details in my head)
E.g
#include <stdio.h>
#include <stdlib.h>
void endproc(void){
remove("removeFile.dat");
}
int main(){
atexit(endproc);
return 0;
}

Passing a variable to chdir() in C (Linux) [duplicate]

This question already has answers here:
Changing working directories in Linux shell in a C program
(2 answers)
Closed 7 years ago.
I'm having a problem with chdir() in my C program - only when running on Linux (works fine on Mac). I've stripped down my code.
Something like this works fine:
chdir("/Documents");
but when I try to pass it as a variable it doesn't want to work.
char *home_directory;
home_directory = malloc(80);
chdir(home_directory);
Home directory is read from a file elsewhere in my code, I can post how I've done that if needed.
Thanks.
Since you are reading home_directory from a file, have you forgotten to remove a trailing newline and any other spurious characters before you use it as a parameter to chdir?
Try doing some error checking, like this;
char *home_directory;
home_directory = malloc(80);
/* ...fill the home directory... */
if (chdir(home_directory) == -1)
perror("chdir");
.. and then with a man chdir yo can look up the meaning of the error code.
Since chdir is a system call on Linux, you can simply use the strace program to see what your program really does. That doesn't free you from handling errors preoperly in your code; obviously. It just helps you to follow the actions that your program takes.

running shell script using c programming

hello every one I want to ask that I am making a program in which i have to run shell script using c program. up till now i have separated the arguments. and i have searched that exec should be use to run shell scripts
but i am totally confused as there are many variants of exec and by reading the man pages i am unable to find which is best suitable
Also in some exec function first arg is
path
and some have
pointer to file
what is the difference and what should i write in place of it.kindly guide me
thanks
Running a shell script from a C program is usually done using
#include <stdlib.h>
int system (char *s);
where s is a pointer to the pathname of the script, e.g.
int rc = system ("/home/username/bin/somescript.sh");
If you need the stdout of the script, look at the popen man page.
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
for ((i=0 ; i < 10 ; i++))\n\
do\n\
echo \"Count: $i\"\n\
done\n\
"
int main(void)
{
puts("Will execute sh with the following script:");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT);
return 0;
}
Reference:
http://www.unix.com/programming/216190-putting-bash-script-c-program.html
All exec* library functions are ultimately convenience wrappers over the execve() system call. Just use the one that you find more convenient.
The ones that end in p (execlp(), execvp()) use the $PATH environment variable to find the program to run. For the others you need to use the full path as the first argument.
The ones ending in e (execle(), execve()) allow you to define the environment (using the last argument). This way you avoid potential problems with $PATH, $IFS and other dangerous environment variables.
The ones wih an v in its name take an array to specify arguments to the program to run, while the ones with an l take the arguments to the program to run as variable arguments, ending in (char *)NULL. As an example, execle() is very convenient to construct a fixed invocation, while execv* allow for a number of arguments that varies programatically.

Resources