How do I insert the result of system() in a string? - c

I'd like to insert the result of the command system("echo %username%"); in a string, but I can't figure out how I could do it in C. Can someone please help me?

Adapted from this C++ solution and a little bit more flexible than August Karlstroms answer you can do something like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define S_SIZE 128
char * exec(const char* cmd)
{
FILE* pipe = _popen(cmd, "r"); // open a pipe to the command
if (!pipe) return NULL; // return on Error
char buffer[S_SIZE];
int size = S_SIZE;
char * result = NULL;
while (fgets(buffer, 128, pipe) != NULL)
{
result = realloc(result, size); // allocate or reallocate memory on the heap
if (result && size != S_SIZE) // check if an error occured or if this is the first iteration
strcat(result, buffer);
else if (result)
strcpy(result, buffer); // copy in the first iteration
else
{
_pclose(pipe);
return NULL; // return since reallocation has failed!
}
size += 128;
}
_pclose(pipe);
return result; // return a pointer to the result string
}
int main(void)
{
char* result = exec("echo %username%");
if (result) // check for errors
{
printf("%s", result); // print username
free(result); // free allocated string!
}
}

Use the POSIX function popen:
#include <stdio.h>
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
int main(void)
{
FILE *f;
char s[32];
const char *p;
f = popen("echo august", "r");
p = fgets(s, LEN(s), f);
if (p == NULL) {
s[0] = '\0';
}
pclose(f);
puts(s);
return 0;
}

Related

Read a file using "read()" function

i'm studying C, and I need to read a text-file, but I can only use "write, malloc, free, open, read, close".
That's my code:
#define MAXCHAR 10000
int open_fp(int check)
{
char *int_vector;
int fp,len;
int i,j;
char buffer[MAXCHAR];
if(check == 0) //standard list
{
if((fp = open("file.txt", O_RDONLY)) != -1) //check if the fp is opened. -1 = error
{
printf("\n%d\n",fp); // DEBUG FUNCTION
sleep(1);
if (!(int_vector = (char*)malloc(sizeof(char) * sizeof(char))))
{
printf("\nWrong allocation\n!"); // DEBUG FUNCTION
return(0);
}
len = read(fp,int_vector,MAXCHAR);
for(i=0;i<len;i++)
{
printf("%c",int_vector[i]);
}
}
else
{
printf("File error!");
return (0);
}
}
return(0);
}
Now my question is: As you can read here,
char buffer[MAXCHAR];
i've created static buffer, but i would like create a dynamic buffer which allow me to resize the buffer according to the number of the chars in the text file, but i don't know how... someone have a trick😥😥 ?
First of all your way of allocating memory is wrong in below line.
//This allocates only 2 bytes of memory, but you are trying to read 10000
if (!(int_vector = (char*)malloc(sizeof(char) * sizeof(char))))
correct that line as below
//better to add one byte extra and store \0 at the end, useful in case of string operations
if (!(int_vector = malloc(MAXCHAR+1)))
and as far as your question is concerned, you dont need to reallocate memory in this particular case because you are just reading the bytes to buffer and printing.
a single malloc will suffice.
#include<stdlib.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAXCHAR 100
int open_fp(int check)
{
char *int_vector;
int fp,len;
int i,j;
char buffer[MAXCHAR];
if(check == 0) //standard list
{
if((fp = open("file.txt", O_RDONLY)) != -1) //check if the fp is opened. -1 = error
{
printf("\n%d\n",fp); // DEBUG FUNCTION
sleep(1);
if (!(int_vector = (char*)malloc(MAXCHAR)))
{
printf("\nWrong allocation\n!"); // DEBUG FUNCTION
return(0);
}
//not doing memset on purpose because only limited bytes are accessed.
while(len = read(fp,int_vector,MAXCHAR))
{
printf("\n **number of bytes read is %d **\n",len);
for(i=0;i<len;i++)
{
printf("%c",int_vector[i]);
}
}
printf(" At last LEN = %d\n", len);
//free the memory at the end
free(int_vector);
int_vector = NULL;
close(fp);// better to as fd
}
else
{
printf("File error!\n");
return (0);
}
}
return(0);
}
int main()
{
open_fp(0);
return 0;
}
ehm, If you forget to set realloc to it as well, here is some sample code for reallocation (dynamic resizing buffer)
#include <stdio.h>
#include <stdlib.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}

Weird C segmentation fault

So I have this bit of code
int main(int argc, char *argv[]) {
char *vendas[1];
int size = 1;
int current = 0;
char buffer[50];
char *token;
FILE *fp = fopen("Vendas_1M.txt", "r");
while(fgets(buffer, 50, fp)) {
token = strtok(buffer, "\n");
if (size == current) {
*vendas = realloc(*vendas, sizeof(vendas[0]) * size * 2);
size *= 2;
}
vendas[current] = strdup(token);
printf("%d - %d - %s\n", current, size, vendas[current]);
current++;
}
}
Here's the thing... Using GDB it's giving a segmentation fault on
vendas[current] = strdup(token);
but the weirdest thing is it works up until the size it at 1024. The size grows up to 1024 and then it just spits a segmentation fault at around the 1200 element.
I know the problem is on the memory reallocation, because it worked when I had a static array. Just can't figure out what.
You cannot reallocate a local array, you want vendas to be a pointer to an allocated array of pointers: char **vendas = NULL;.
You should also include the proper header files and check for fopen() and realloc() failure.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
void free_array(char **array, size_t count) {
while (count > 0) {
free(array[--count]);
}
free(array);
}
int main(int argc, char *argv[]) {
char buffer[50];
char **vendas = NULL;
size_t size = 0;
size_t current = 0;
char *token;
FILE *fp;
fp = fopen("Vendas_1M.txt", "r");
if (fp == NULL) {
printf("cannot open file Vendas_1M.txt\n");
return 1;
}
while (fgets(buffer, sizeof buffer, fp)) {
token = strtok(buffer, "\n");
if (current >= size) {
char **savep = vendas;
size = (size == 0) ? 4 : size * 2;
vendas = realloc(vendas, sizeof(*vendas) * size);
if (vendas == NULL) {
printf("allocation failure\n");
free_array(savep, current);
return 1;
}
}
vendas[current] = strdup(token);
if (vendas[current] == NULL) {
printf("allocation failure\n");
free_array(vendas, current);
return 1;
}
printf("%d - %d - %s\n", current, size, vendas[current]);
current++;
}
/* ... */
/* free allocated memory (for cleanliness) */
free_array(vendas, current);
return 0;
}
You only have room for one (1) pointer in you array of char *vendas[1]. So second time around you are outside the limits of the array and are in undefined behavior land.
Also, the first call to realloc passes in a pointer that was not allocated by malloc so there is another undefined behavior.

C programming: lines of text file to integer array

I want to change my input.txt file to an integer array.
But sadly I keep missing one integer whenever new-line-character is met.
Following is my main()
int main(int args, char* argv[]) {
int *val;
char *STRING = readFile();
val = convert(STRING);
return 0;
}
Following is my file input function
char *readFile() {
int count;
FILE *fp;
fp = fopen("input.txt", "r");
if(fp==NULL) printf("File is NULL!n");
char* STRING;
char oneLine[255];
STRING = (char*)malloc(255);
assert(STRING!=NULL);
while(1){
fgets(oneLine, 255, fp);
count += strlen(oneLine);
STRING = (char*)realloc(STRING, count+1);
strcat(STRING, oneLine);
if(feof(fp)) break;
}
fclose(fp);
return STRING;
}
Following is my integer array function
int *convert(char *STRING){
int *intarr;
intarr = (int*)malloc(sizeof(int)*16);
int a=0;
char *ptr = strtok(STRING, " ");
while (ptr != NULL){
intarr[a] = atoi(ptr);
printf("number = %s\tindex = %d\n", ptr, a);
a++;
ptr = strtok(NULL, " ");
}
return intarr;
}
There are many issues.
This is a corrected version of your program, all comments are mine. Minimal error checking is done for brevity. intarr = malloc(sizeof(int) * 16); will be a problem if there are more than 16 numbers in the file, this should be handled somehow, for example by growing intarr with realloc, similar to what you're doing in readFile.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char *readFile() {
FILE *fp;
fp = fopen("input.txt", "r");
if (fp == NULL)
{
printf("File is NULL!n");
return NULL; // abort if file could not be opened
}
#define MAXLINELENGTH 255 // define a constant rather than hardcoding "255" at several places
char* STRING;
char oneLine[MAXLINELENGTH];
STRING = malloc(MAXLINELENGTH);
int count = MAXLINELENGTH; // count mus be initialized and better declare it here
assert(STRING != NULL);
STRING[0] = 0; // memory pointed by STRING must be initialized
while (fgets(oneLine, MAXLINELENGTH, fp) != NULL) // correct usage of fgets
{
count += strlen(oneLine);
STRING = realloc(STRING, count + 1);
strcat(STRING, oneLine);
}
fclose(fp);
return STRING;
}
int *convert(char *STRING, int *nbofvalues) { // nbofvalues for returning the number of values
int *intarr;
intarr = malloc(sizeof(int) * 16);
int a = 0;
char *ptr = strtok(STRING, " \n"); // strings may be separated by '\n', or ' '
*nbofvalues = 0;
while (ptr != NULL) {
intarr[a] = atoi(ptr);
printf("number = %s\tindex = %d\n", ptr, a);
a++;
ptr = strtok(NULL, " \n"); // strings are separated by '\n' or ' '
} // read the fgets documentation which
// terminates read strings by \n
*nbofvalues = a; // return number of values
return intarr;
}
int main(int args, char* argv[]) {
int *val;
char *STRING = readFile();
if (STRING == NULL)
{
printf("readFile() problem\n"); // abort if file could not be read
return 1;
}
int nbvalues;
val = convert(STRING, &nbvalues); // nbvalues contains the number of values
// print numbers
for (int i = 0; i < nbvalues; i++)
{
printf("%d: %d\n", i, val[i]);
}
free(val); // free memory
free(STRING); // free memory
return 0;
}
I'm not sure what your requirement is, but this can be simplified a lot because there is no need to read the file into memory and then convert the strings into number. You could convert the numbers on the fly as you read them. And as already mentioned in a comment, calling realloc for each line is inefficient. There is room for more improvements.

Pointer issue not solved

In the below code, the file test.txt has the following data :
192.168.1.1-90
192.168.2.2-80
The output of this is not as expected. I expect the output to be
192.168.1.1
90
192.168.2.2
80
The current output is
192.168.2.2
80
192.168.2.2
80
I know that the pointer of str is pointing to the same address in the second iteration as well.
Im just not able to the problem.
Any help would be appreciated.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE * fp;
char * result[10][4];
int i = 0;
const char s[2] = "-";
char temp[50];
char * value, str[128], * string, t[20], x[29] = "192.168.2.2";
fp = fopen("test.txt", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else {
while (!feof(fp)) {
if (fgets(str, sizeof(str), fp)) {
/* get the first value */
value = strtok(str, s);
result[i][0] = value;
printf("IP : %s\n", result[i][0]); //to be removed after testing
/* get second value */
value = strtok(NULL, s);
result[i][1] = value;
printf("PORT : %s\n", result[i][1]); //to be removed after testing
i++;
}
}
for (int k = 0; k < 2; k++) {
for (int j = 0; j < 2; j++) {
printf("\n%s\n", result[k][j]);
}
}
}
return (0);
}
I propose like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { IP = 0, PORT = 1};
int main(void){
FILE *fp;
char result[2][2][16];//2 lines, 2 kinds, 16:XXX.XXX.XXX.XXX+NUL
const char *s = "-";//delimiter
char *value, line[128];
int i=0;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("File doesn't exist\n");
exit(EXIT_FAILURE);
}
while(i < 2 && fgets(line, sizeof(line), fp)){
value = strtok(line, s);
strcpy(result[i][IP], value);
printf("IP : %s\n",result[i][IP]);
value = strtok(NULL, s);
strcpy(result[i][PORT], value);
printf("PORT : %s\n",result[i][PORT]);
i++;
}
puts("");
for (int k=0;k<2;k++){
for (int j=0;j<2;j++){
printf("%s\n",result[k][j]);
}
}
fclose(fp);
return 0;
}
What you are doing wrong is that you are assigning "value" pointer to elements of "result" array. In your implementation, all the elements of "result" just mirror the value of "value" pointer. Therefore, when you change the value of "value", you also change all the "result" elements.
Because of that, you should use strcpy function after allocating memory for the specific "result" element.
value = strtok(str, s);
result[i][0]=malloc(strlen(value) + 1);
strcpy(result[i][0], value);
When you want to keep-copy strings you have to use the function strcpy()
Instead of result[i][x] = value you should do the following
strcpy(result[i][x], value);
Edit: Before the strcpy you have to use malloc to allocate memory for the result[i][x] string.
eg:
result[i][0] = malloc(10 * sizeof(char));
I suggest using malloc for allocating space for each ip and port, and freeing them at the end with free. Additionally, a struct might be handy here, if you have bigger text files in the future that you want to use.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COLS 2
#define MAXCHAR 10
#define BUFFSIZE 128
void exit_if_null(void *ptr, const char *msg);
int
main(void) {
FILE *filename;
char *result[COLS][MAXCHAR+1];
char buffer[BUFFSIZE];
char *ip, *port;
int row, i = 0;
filename = fopen("ips.txt", "r");
if (filename == NULL) {
fprintf(stderr, "%s\n", "Error reading file!\n");
exit(EXIT_FAILURE);
} else {
while (fgets(buffer, BUFFSIZE, filename) != NULL && i < 2) {
ip = strtok(buffer, "-");
port = strtok(NULL, "\n");
result[i][0] = malloc(strlen(ip)+1);
exit_if_null(result[i][0], "Initial Allocation");
result[i][1] = malloc(strlen(port)+1);
exit_if_null(result[i][1], "Initial Allocation");
strcpy(result[i][0], ip);
strcpy(result[i][1], port);
i++;
}
}
for (row = 0; row < i; row++) {
printf("%s\n", result[row][0]);
printf("%s\n", result[row][1]);
free(result[row][0]);
free(result[row][1]);
result[row][0] = NULL;
result[row][1] = NULL;
}
return 0;
}
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}

strtok and storage in arrays: output not as expected

In the below code, the file test.txt has the following data :
192.168.1.1-90
192.168.2.2-80
The output of this is not as expected.
I expect the output to be
192.168.1.1
90
192.168.2.2
80
Any help would be much appreciated.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char *result[10][4];
int i=0;
const char s[2] = "-";
char *value,str[128];
fp = fopen("test.txt", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else{
while(!feof(fp)){
if(fgets(str,sizeof(str),fp)){
/* get the first value */
value = strtok(str, s);
result[i][0]=value;
printf("IP : %s\n",result[i][0]); //to be removed after testing
/* get second value */
value = strtok(NULL, s);
result[i][1]=value;
printf("PORT : %s\n",result[i][1]); //to be removed after testing
i++;
}}
for (int k=0;k<2;k++){
for (int j=0;j<2;j++){
printf("\n%s\n",result[k][j]);
}
}
}
return(0);
}
You can try this solution. It uses dynamic memory instead, but does what your after.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 128
void exit_if_null(void *ptr, const char *msg);
int
main(int argc, char const *argv[]) {
FILE *filename;
char buffer[BUFFSIZE];
char *sequence;
char **ipinfo;
int str_size = 10, str_count = 0, i;
filename = fopen("ips.txt", "r");
if (filename == NULL) {
fprintf(stderr, "%s\n", "Error Reading File!");
exit(EXIT_FAILURE);
}
ipinfo = malloc(str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Initial Allocation");
while (fgets(buffer, BUFFSIZE, filename) != NULL) {
sequence = strtok(buffer, "-\n");
while (sequence != NULL) {
if (str_size == str_count) {
str_size *= 2;
ipinfo = realloc(ipinfo, str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Reallocation");
}
ipinfo[str_count] = malloc(strlen(sequence)+1);
exit_if_null(ipinfo[str_count], "Initial Allocation");
strcpy(ipinfo[str_count], sequence);
str_count++;
sequence = strtok(NULL, "-\n");
}
}
for (i = 0; i < str_count; i++) {
printf("%s\n", ipinfo[i]);
free(ipinfo[i]);
ipinfo[i] = NULL;
}
free(ipinfo);
ipinfo = NULL;
fclose(filename);
return 0;
}
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}
The key thing to understand is that char *strtok(char *str, const char *delim) internally modifies the string pointed to by str and uses that to store the result. So the returned pointer actually points to somewhere in str.
In your code, the content of str is refreshed each time when you parse a new line in the file, but the address remains the same. So after your while loop, the content of str is the last line of the file, somehow modified by strtok. At this time, result[0][0] and result[1][0] both points to the same address, which equals the beginning of str. So you print the same thing twice in the end.
This is further illustrated in the comments added to your code.
int main()
{
FILE *fp;
char *result[10][4];
int i=0;
const char s[2] = "-";
char *value,str[128];
fp = fopen("test.txt", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else{
while(!feof(fp)){
if(fgets(str,sizeof(str),fp)){
/* get the first value */
value = strtok(str, s);
// ADDED: value now points to somewhere in str
result[i][0]=value;
// ADDED: result[i][0] points to the same address for i = 0 and 1
printf("IP : %s\n",result[i][0]); //to be removed after testing
/* get second value */
value = strtok(NULL, s);
// ADDED: value now points to somewhere in str
result[i][1]=value;
// ADDED: result[i][1] points to the same address for i = 0 and 1
printf("PORT : %s\n",result[i][1]); //to be removed after testing
i++;
}}
// ADDED: now result[0][0]==result[1][0], result[0][1]==result[1][1], you can test that
for (int k=0;k<2;k++){
for (int j=0;j<2;j++){
printf("\n%s\n",result[k][j]);
}
}
}
return(0);
}
To get the expected output, you should copy the string pointed by the pointer returned by strtok to somewhere else each time, rather than just copy the pointer itself.

Resources