Using popen to read and write in C using two executables - c

I understand that popen doesn't allow simultaneous read and write.
To get around this, I created two files, 1.c for writing, and 2.c for reading. The files are included below.
When I run 1.out, I get the expected output on stdout:
bodhi#bodhipc:~/Downloads$ ./1.out
Stockfish 11 64 BMI2 by T. Romstad, M. Costalba, J. Kiiski, G. Linscott
bodhi#bodhipc:~/Downloads$
However, 2.out doesn't give any output on stdout:
bodhi#bodhipc:~/Downloads$ ./2.out
bodhi#bodhipc:~/Downloads$
Where am I going wrong?
1.c:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for writing. */
fp = popen("./stockfish", "w");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
fprintf(fp,"uci\n");
/* close */
pclose(fp);
return 0;
}
2.c:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("./1.out", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it.*/
while (fgets(path, sizeof(path), stdout) != NULL) {
printf("%s", path);
printf("Done!\n");
}
/* close */
pclose(fp);
return 0;
}

while (fgets(path, sizeof(path), stdout) != NULL) {
you don't want to read from stdout, instead:
while (fgets(path, sizeof(path), fp) != NULL) {

Related

Unable to save a char array using fprintf()

I am unable to save a char array using fprint() and i cannot figure out why. The below codes compliles correctly but saves nothing to file. Please advise.
static char bitSpecial[100];
int main(int argc, char *argv[]) {
FILE *fp
fp = fopen(thefilename, "w+");
if (fp == NULL) {
printf("I couldn't open file for writing.\n");
exit(0);
}
/* populate bitSpecial one character at the time and verify array is full */
fprintf(fp,"%s", bitSpecial);
if (fclose(fp) != 0) puts("Unable to close the file");
return
}
It'll be easier to identify the problem with the full code. I tried the following snippet and it worked:
#include <stdio.h>
#include <string.h> // for strerror
#include <errno.h> // for errno
static char bitSpecial[100];
int main(int argc, char *argv[])
{
char * thefilename = "test";
FILE *fp;
fp = fopen(thefilename, "w+");
if (fp == NULL) {
printf("I couldn't open file for writing.\n");
return 1;
}
/* populate bitSpecial one character at the time and verify array is full */
bitSpecial[0] = 'a';
bitSpecial[1] = '\n';
bitSpecial[2] = '\0'; // terminator
if (fprintf(fp,"%s", bitSpecial) < 0)
printf("[+] fprintf failed with '%s'\n", strerror(errno));
if (fclose(fp) != 0)
puts("Unable to close the file");
return 0;
}
Verify that you put a null terminator (\0) at the end of bitSpecial, and check the return value of fprintf.

Debugging C program with two arguments passed

I have fixed some syntactical errors in my code and now the program compiles fine. But when I execute the program the outputFile is empty. outputFile should have contents of inputFile in reverse order. I am trying to debug code in CodeLite IDE.
I need to debug the code with two arguments passed (inputFile and outputFile). I don't seem to find that option in CodeLite IDE. How do I do that ?
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 256
int main (int argc, char *argv[]){
FILE *inputFile, *outputFile;
int fileSize;
int pointer;
char buffer[BUFFER_SIZE];
/* Check for correct user's inputs. */
if( argc !=3 ) {
fprintf(stderr, "USAGE: %s inputFile outputFile.\n", argv[0]);
exit(-1);
}
/* Make sure input file exists. */
if( (inputFile = fopen(argv[1], O_RDONLY))) {
fprintf(stderr, "Input file doesn't exist.\n");
exit(-1);
}
/* Create output file, if it doesn't exist. Empty the file, if it exists. */
if((outputFile = fopen(argv[2], "a+"))) {
fclose(inputFile);
exit(-1);
}
/* Find the size of the input file. */
fileSize = fseek(inputFile, 0, SEEK_END);
/* Read input file and write to output file in reversed order.*/
for(pointer=fileSize-1; pointer>=0; pointer--) {
/*Write content in the buffer to the output file */
while(!feof(inputFile))
{
fgets(buffer, BUFFER_SIZE, inputFile); //reads 256 bytes at a time
fputs (buffer , outputFile );
}
}
fclose(inputFile);
fclose(outputFile);
return(0);
}
http://codelite.org/LiteEditor/ProjectSettings:
Project Settings >> General >> Command arguments
Right click on the project folder
Select project settings
General -> Execution -> Program Arguments

fopen: file does not exist but it does

I want to read all files that I can find in the folder where my executable is, except the runnable file that I'm running. I code the following code but, although this list correctly the files that I have in my folder, I cannot open them with fopen because fopen prints that the file doesn't exists. If I do gedit "path of the file obtained from my program in c" then it opens perfectly from the term. Where is the bug?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
int main (int argc, char **argv) {
//Determining the number of files we have.
//We call to a bash command http://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output
FILE *fp, *fin;
char path[1035], cwd[1024];
int scanned = 0;
/* Open the command for reading. */
//https://askubuntu.com/questions/370697/how-to-count-number-of-files-in-a-directory-but-not-recursively
//This count soft and hard links also (I think)
fp = popen("ls -F |grep -v /", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
//Loop for each file. Be careful! if the exe is inside, it will also be counted!
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("Reading file: %s\n", path);
fin=fopen(path,"r");
scanned = 0;
printf("caa");
if (fin != NULL){
printf("AA\n");
fclose(fin);
}
if (!fin)perror("fopen");
printf("Done! \n");
}
/* close */
pclose(fp);
printf("end");
return 0;
}
There are 2 bugs in your code:
when the code updates the "path" variable in your code. It has a newline at the end which needs to be corrected to NUL. This gives an incorrect path.
Something like below can be appended to your code:
while (fgets(path, sizeof(path)-1, fp) != NULL) {
len=strlen(path);
path[len-1]='\0';
Use 'ls -A1', since 'ls -F' adds a '*' in binary name:
fp = popen("ls -A1 |grep -v /", "r");
ok so just in case someone else needs a better approach, I redid the code with the comments I had. Here I let you the new code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
int main (int argc, char **argv) {
FILE *fp, *fin;
char path[1035], cwd[1024];
int scanned = 0;
int ints;
DIR *dir;
struct dirent *ent;
//getcwd prints directory where the app ran.
if ((dir = opendir (getcwd(cwd, sizeof(cwd)))) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
/*Skips . and ..*/
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
if (isDirectory(ent->d_name) != 0) continue;
printf ("Reading file: %s\n", ent->d_name);
scanned = 0;
fin=fopen(ent->d_name,"r");
if (fin != NULL){
while ((scanned = fscanf(fin, "%d", ints)) != EOF) {
if(scanned == 1){
printf("%d\n", ints);
}else {
printf("Whoops! Input format is incorrect!\n");
break;
}
} //LOOP: reading file
fclose(fin);
}
if (!fin)perror("fopen");
printf("Done! \n");
}//LOOP: while opendir
closedir (dir);
} else {
/* could not open directory */
perror ("opendir");
return EXIT_FAILURE;
}
return 0;
}

how to copy result of the linux command into a string using c code?

I have executed a command "watch grep \"cpu MHz \" /proc/cpuinfo".After executing this command i got following result.
Result of The Command
But when I am trying this command using c code.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char path[1035];
char command[]="watch grep \"cpu MHz \" /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
I am getting following result.
Result of The Code
tell me where am I going wrong?
Try something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp;
char path[1035];
char command[]="while grep \"cpu MHz\" /proc/cpuinfo; do sleep 2; done";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
I think this is what you want.
Don't forget to use memset.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char path[1035];
char command[]="watch grep 'cpu MHz' /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
memset(path,'\0',sizeof(path));
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}

Simulate the Linux command tee in C

I have to do the simulation of the command tee in C for Linux. How does tee work internally? It looks like a T-shaped pipe, so should I use a pipe? Is there a special kind of pipe?
tee takes stdin and copies the data stream to stdout as well as a file given as an option, it can be used in many very different situations.
An implementation in C is quite simple, just make a program that copies all data from stdin to stdout, but also use the same output statements for stdout on a file that you opened based on the command line argument.
basically in pseudo code:
file f = open(argv[1])
while (! end of file stdin) {
buffer = read stdin
write stdout buffer
write f buffer
}
close(f)
Note that you don't really have to do anything with pipes, your shell will sort out the pipes, the program only has to copy data from one stream to two others.
I finished the program!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(int argc, char *argv[]){
FILE *fp, *fp1;
char buffer;
if(argc != 4){
printf("\nError");
printf("\nSintaxis: tee [archivo1] [archivo2]\n");
exit(0);
}
if(strcmp(argv[1], "tee") == 0){
fp = fopen(argv[2], "r");
fp1 = fopen(argv[3], "w");
printf("\Content in %s:\n", argv[2]);
while(!feof(fp)){
buffer = fgetc(fp);
fputc(buffer, fp1);
printf("%c", buffer);
}
printf("\n\n%s received %s\n", argv[3], argv[2]);
fclose(fp);
fclose(fp1);
}
else
printf("\nThe first argument have to be tee\n");
}
Here is some code I wrote about 20 years ago to implement TEE in Windows. I have been using this with various batch files since then. Note the flush command at the end of each line.
#include <stdio.h>
#include <share.h>
int main (int argc, char * argv[])
{
if (argc < 2 )
{
printf ("Error: No output file name given, example: theCmd 2>&1 |ltee outputFileName \n");
return 1;
}
FILE *Out = _fsopen(argv[argc-1], "a", _SH_DENYWR);
if (NULL == Out)
{
char buf[300];
sprintf_s(buf, 300, "Error openning %s", argv[argc-1]);
perror(buf);
return 1;
}
int ch;
while ( EOF != (ch=getchar()))
{
putchar(ch);
putc(ch, Out);
if ( '\n' == ch )
fflush(Out);
}
_flushall();
fclose(Out);
return 0;
}

Resources