Save information from sprintf to a variable - c

is it possible to save information gather from a sprintf into a variable? The lines of code below are an example to better illustrate my question.
char fileName;
fileName = sprintf(command, "find -inum %i -type f", iNode);
The purpose is to find the file name associated with the inode number, then run "stat" on that file name.

I think you want something like this:
FILE *fp;
char cmd[1024];
char filename[1024];
sprintf(cmd, "find -inum %i -type f", iNode);
fp = popen(cmd);
fgets(filename, sizeof filename, fp);
pclose(fp);
At the end of this code, filename will contain the fist line produced by the cmd.

Related

Specify file extension

Right now, what I have is this:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char fname[100];
FILE* fp;
memset(fname, 0, 100);
/* ask user for the name of the file */
printf("enter file name: ");
gets(fname);
fp = fopen(fname, "w");
/* Checks if the file us unable to be opened, then it shows the
error message */
if (fp == NULL)
printf("\nError, Unable to open the file for reading\n");
else
printf("hello");
getch();
}
This functions just fine, but is there a way I can force it to save as a .txt or a .data or something? Right now it just saves as the name you put in with no extension. Other than asking the user to just input the name and extension, I can't think of a way to do that. I mean, it still works just fine for reading/writing purposes, I just think an extension would be nice.
to expand my comment:
strcat(fname, ".txt");
The strcat function can be used to append text to a destination buffer, assuming the destination is large enough to store the new text.
char *strcat(char *destination, const char *source);
The source is the new text that you want to append (in your case the extension), and the destination is where the new text will be added. If destination is not big enough, then the behavior is undefined.
One could also use the snprintf function to append text, which is safer, as it takes a size argument.
I figured it out. Credit goes to a friend of mine who showed this to me earlier today.
int main()
{
FILE *Fileptr;
char filename[50];
char file[50];
int c;
printf("What do you want to name your file?");
scanf("%s", filename);
sprintf(file, "%s.txt", filename);
Fileptr = fopen(file, "w");
fprintf(Fileptr, "Data goes here");
fclose(Fileptr);
return 0;
}
Much easier than what I had been doing.

Variable Substitution in C

I want to open a file. Easy enough. Use fopen(). However, what file to open depends on the user input. I am somewhat proficient in Korn Shell scripting and this is easily done using variable substitution: $(var). I am unable to figure out the correct format in C. Could someone please give me some insight?
My code -
#include <stdlib.h>
#include <stdio.h>
char statsA[100];
char fileA[50];
int main (void)
{
printf("Enter file to open\n");
gets(fileA);
FILE *statsA;
statsA = fopen("c:/Users/SeanA/C/***<fileA>***", "r+");
.......................................^ What goes here?
I am unsure of how to include the user input in the fopen string.
This is what sprintf is for. It works like printf, except that its output goes to a string instead of stdout.
char filename[100];
sprintf(filename, "c:/Users/SeanA/C/%s", fileA);
statsA = fopen(filename, "r+");
Also, the definition of statsA you have inside of main masks the definition at file scope. You probably want to give these different names.
You must concatenate both strings manually. Something like this
char* folder = "c:/Users/SeanA/C/";
char* path = malloc(strlen(fileA) + strlen(folder) + 1);
path = strcpy(folder);
path = strcat(fileA);
FILE *statsA = fopen(path, "r+");
free(path);//Always free your memory
Do scanf to get the file from the user.
make a char array to hold the filename.
char filename[15];
Now ask for the file name:
printf("What is the name of the file?\n");
scanf("%s", &filename);
Note: Include the FULL file name. so if I have a text doc called filename The user would need to type filename.txt
Now you have the file name you can declare a file pointer
FILE * fp;
fp = fopen(filename, "r");
Now you should be able to scan your file!
fscanf(fp, "%d", &value);
EDIT: I did not notice you wanted string concatenation with your file path.
Since you know the predefined path you can make another char array that holds that string path
char fullPath[100];
char path[75] = "c:/Users/SeanA/C/";
Now you can use strcat to bring them all together!
strcat(fullPath, path);
strcat(fullPath, filename);
Now you do fopen(fullPath, "r");

It possible to replace file to buffer while pass input to an exe as shell command?

I'm using "system" API calls to run shell commands in my C program, now
there is case where I want to redirect the output generated by an executableto a buffer instead of a file (named recv.mail)
An example of how I write the output to the file:
cmd[] = "mda "/bin/sh -c 'cat > recv.mail'";
system (cmd);
Similarly I want to replace input taken from the file (send.mail) with input taken from a buffer.
An example of how I take input from a file:
cmd[] = "msmtp < cat send.mail";
system (cmd);
NOTE: The send.mail and recv.mail files have formatted data.
Are pipes a better replacement?
Can anyone suggest another alternative?
popen/pclose may do what you want:
FILE *f = popen("program to execute", "r");
if (NULL != f)
{
char buffer[128];
while (fgets(buffer, sizeof buffer, f)
{
printf("Read from program: '%s'\n", buffer);
}
pclose (f);
}
popen/pclose again:
FILE *f = popen("program to execute", "w");
...

fgets() not working.in C?

Edit: Deleted all but the main question.
My program here is supposed to create a file at a specified directory, and write specified text to it. A correct file's path and content should look something like this:
Path: D:\test.txt
Content: The printing succeeded.
For some reason, my code won't recognize the "path" variable. I don't know what I'm doing wrong here. The "text" variable works fine.
#include<stdio.h>
int main()
{
//Declaring variables
char path[999];
char text[999];
FILE *fp;
//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);
//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);
//opening and printing to file.
//fp = fopen("D:\\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);
//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}
The thing I don't understand is that fp = fopen("D:\\test.txt", "w"); works, but fp = fopen(path, "w"); doesn't. I've tried putting in these different paths.:
D:\\test.txt
D:\test.txt
D\test.txt
D\\test.txt
It doesn't open the file when you open the variable path because fgets() reads the newline and puts it at the end of the string (if there's enough space in the buffer). In order to make it work you have to manually remove the newline from the string.
Try this before opening the file.
if(isspace(path[strlen(path)-1]))
path[strlen(path)-1]='\0';
You might also need to include <ctype.h>

How Do I Pipe a String Into a popen() Command in C?

Im working in c (more or less for the first time) for uni, and I need to generate an MD5 from a character array. The assignment specifies that this must be done by creating a pipe and executing the md5 command on the system.
I've gotten this far:
FILE *in;
extern FILE * popen();
char buff[512];
/* popen creates a pipe so we can read the output
* of the program we are invoking */
char command[260] = "md5 ";
strcat(command, (char*) file->name);
if (!(in = popen(command, "r"))) {
printf("ERROR: failed to open pipe\n");
end(EXIT_FAILURE);
}
Now this works perfectly (for another part of the assignment which needs to get the MD5 for a file) but I cant workout how to pipe a string into it.
If I understand correctly, I need to do something like:
FILE * file = popen("/bin/cat", "w");
fwrite("hello", 5, file);
pclose(file);
Which, I think, would execute cat, and pass "hello" into it through StdIn. Is this right?
If you need to get a string into the md5 program, then you need to know what options your md5 program works with.
If it takes a string explicitly on the command line, then use that:
md5 -s 'string to be hashed'
If it takes standard input if no file name is given on the command line, then use:
echo 'string to be hashed' | md5
If it absolutely insists on a file name and your system supports /dev/stdin or /dev/fd/0, then use:
echo 'string to be hashed' | md5 /dev/stdin
If none of the above apply, then you will have to create a file on disk, run md5 on it, and then remove the file afterwards:
echo 'string to be hashed' > file.$$; md5 file.$$; rm -f file.$$
See my comment above:
FILE* file = popen("/sbin/md5","w");
fwrite("test", sizeof(char), 4, file);
pclose(file);
produces an md5 sum
Try this:
static char command[256];
snprintf(command, 256, "md5 -qs '%s'", "your string goes here");
FILE* md5 = popen(md5, "r");
static char result[256];
if (fgets(result, 256, md5)) {
// got it
}
If you really want to write it to md5's stdin, and then read from md5's stdout, you're probably going to want to look around for an implementation of popen2(...). That's not normally in the C library though.

Resources