Failed to Open source file while system call in C [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to create a call to system using custom parameters. However I think that I am incorrectly malloc-ing the size of the final char*.
So I instead get a Failed to Open source file error during the system call. Am I doing something wrong in terms of syntax?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char program_name[] = "/usr/local/bin/some_program";
char argument_1[] = "foo";
char argument_2[] = "foo2";
char space[] = " ";
char *runProgram = malloc( strlen(program_name) + strlen(argument_1)+
strlen(argument_2) + 2*strlen(space) + 1);
strcpy(runProgram, program_name);
strcat(runProgram, space);
strcat(runProgram, argument_1);
strcat(runProgram, space);
strcat(runProgram, argument_2);
system(runProgram);
free(runProgram);
exit(0);
}

When I run your code, your string appears to contain exactly what it needs to to be called. I do have a suggestion to simplify building it though:
...
int ret=0;
int len = strlen(program_name) + strlen(argument_1)+ strlen(argument_2) + 2*strlen(space) + 1;
char *runProgram = malloc( len);
ret = snprintf(runProgram, len, "%s %s %s", program_name, argument_1, argument_2);
if(ret < 0)
{
//handle if truncation occurred (returns -1 for truncation)
}
if(ret >= len)
{
//use runProgram buffer
}
system(runProgram);
free(runProgram);
//exit(0);
return 0;
...
Have you verified the chmod settings on the file to be executed are correct?
chmod +x /usr/local/bin/some_program
EDIT:
To address concern in comments regarding variations in implementation/documentation for snprintf(). When discussing standard C functions, the hope would be that implementations of the same function would be equal across platforms, but for snprintf(), it appears that some implementations are more equal than others...
1) snprintf some have referred to this as Microsoft's broken implementation.
2) snprintf from skrenta.com
3) snprintf from opengroup.org.
4) snprintf from linux.die.net, (includes glibc references, macros and other comments)

Your code should work fine, printf("cmd is '%s'\n", runProgram); to check if generated command can be run in shell and produces expected results:
command string is correct
/usr/local/bin/some_program exists and has correct permissions
some_program does not fail

Related

To many arguments in function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm writing a program that checks who the user is, if it's the correct user logged in it will upload data to my FTP server. It encrypts the data using tar, than openssl. I think that part is correct however when passing system commands to the terminal I'm having an issue with strcpy. I keep getting an error that "there are to many arguments to function strcpy. Specifically where it says "strcpy(encrypt, "tar -cf /home/%s", p);" I think it's because I'm passing the variable p to it. Could anyone assist. Thank you.
int main(int argc, char *argv[])
{
// checks to see who the user is
char *p=getenv("USER");
if (p=NULL) return EXIT_FAILURE;
printf("User is %s\n", p);
char *usr;
char *encrypt;
char *upload;
//encrypts folder using tar, then openssl AES 256 bit
strcpy(encrypt, "tar -cf /home/%s", p);
system(encrypt);
strcpy(encrypt, "openssl enc -aes-256-cbc -in FILE.NAME -out file.enc");
system(encrypt);
// uploads data to ftp server using curl
strcpy(upload, "curl -T /PATH/ SERVER_ADDRESS");
system(upload);
return 0;
}
you used strcpy incorrectly as compiler log the error
this is strcpy prototype
char * strcpy ( char * destination, const char * source );
if you want to copy from source to destination when source is a pattern ->
you need to replace strcpy with sprintf or snprintf
for more detail you can check this https://linux.die.net/man/3/snprintf
additional, you haven't allocateed for
char *usr;
char *encrypt;
char *upload;
use malloc or calloc for these things before use

C reading a file with null in it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm working on a data file that contains a fixed number of characters followed by a colon and then a number. All of the first four characters can be anything from all nulls to all (char)255s.
However, when trying to read it, I'm having trouble determining the EOF.
If I use posix's read(2) like so:
ssize_t letters_read = read(fd, buf, 4);
Then letters_read is set to 0. The man page says that means I've reached an EOF; however, this is simply not true.
If I use fread(3) in a similar way, then I still get zero as a return value. Even when sending the file to feof(3), it says I'm at the end of file.
Now, if I just ignore the return values, then I'm able to continue reading the file and get further results.
How would I be able to read all four nulls and still be able to know when I've reached an eof?
A small excerpt of the file looks like this:
4
(null)(null)(null)(null):4
(null)(null)(null)(null):40
(null)(null)(null)(null):402
Af*8:3004
UPDATE
As per request, here is how I'm going about collecting data:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void process_characters(char *data);
int main(int argc, char *argv[])
{
char *input_file = argv[1];
int opt = 0;
int input_fd = open(input_file, O_RDONLY);
FILE *temp_fd = fopen(input_file, "r");
unsigned long character_size = 0;
fscanf(temp_fd, "%l", character_size);
char data[character_size];
//gobble up the first line
do
{
read(input_fd, data, 1);
printf("%i\n", data[0]);
} while(data[0] != '\n');
size_t characters_read = 0;
characters_read = read(input_fd, data, character_size);
//while(feof(temp_fd) != 0)
while(characters_read != 0)
{
//fread(data, sizeof(char), character_size, temp_fd);
process_characters(data);
///gobble up the garbage
do
{
read(input_fd, data, 1);
printf("%i\n", data[0]);
}while(data[0] != 10);
characters_read = read(input_fd, data, character_size);
}
fclose(temp_fd);
close(input_fd);
return EXIT_SUCCESS;
}
This code:
unsigned long character_size = 0;
fscanf(temp_fd, "%l", character_size);
... has an invalid format specified, and needs to provide the variable address rather than its value. "%l" does not specify a type to read. Perhaps you want "%lu" which is for an unsigned long integer, which is how character_size is defined. character_size should be &character_size.
However, there is no such (decimal) value at the beginning of the sample file you have provided, so it is unclear what this fscanf line is really supposed to do.
(You claimed that using read as follow returns 0:
ssize_t letters_read = read(fd, buf, 4);
However, there is no such line in your code).

confusion while understanding parameters of main [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
while understanding the parameters of main function i.e, int argc, char* argv[]
i wrote a piece of code to understand these parameters.
#include <stdio.h>
int main(int argc,char*argv[])
{
printf("test\n");
printf("%d %c",argc,*argv[argc-1]);
return 0;
}
This prints
test
1 F
here I don't understand why there is F as output. I mean how this is executed to result in output as F ?
I read about these perameters and main function at here and here. But still I don't understand how these works.
please explain .
EDIT: as mentioned in comments if I change the code to
printf("%d %s",argc,argv[argc-1]);
Now i'm getting the whole path of the file F:\file path
so does it mean argv[0] is the location of the file in drive?
It is not defined in the C standard, but on Unix argv[0] is the name of the executable. Then argv[1] the first argument, etc. I think that this is also true, most of the time, on Microsoft's Dos and their Windowing OSes.
In simple words:
When you give your commandline the instruction to run your program, you can append some text, which can be accessed in your program.
#include <stdio.h>
int main(int argc,char*argv[])
{
printf("This is the path or name of your programm: ");
printf("%s\n", argv[0]);
if(argc > 1) {
printf("This is the first argument you gave your programm: ");
printf("%s\n", argv[1]);
}
if(argc > 2) {
printf("This is the second argument you gave your programm: ");
printf("%s\n", argv[2]);
}
return 0;
}
Try to run this example with:
<path_to_the_programm> Hallo Welt
You will see argc is an integer, which tells you how many arguments you gave the program. I hope it helped you.

perror() or own string output to stderr in C [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is there a preferable way to report errors in C? For example if a file that is supposed to be opened does not exist, should I use
if( fp == NULL )
{
perror("Error: ");
return(-1);
}
(copied from http://www.tutorialspoint.com/c_standard_library/c_function_perror.htm )
or
if( fp == NULL )
{
fprintf(stderr, "Unable to open file for reading.\n");
return(-1);
}
You can use perror() or strerror to get the error message. If you want to postpone the display of error message or if you want to log the message to a file, then save the errno and use strerror() because perror only writes to the standard error stream and it uses the global errno set and the errno might change any time if any library function is called before printing the error message.
Example using saved errno:
int savederrno;
....
if( fp == NULL )
{
savederrno = errno; /* Save the errno immediately after an api/lib function or a system call */
/*If you want to write to a log file now, write here using strerror and other library calls */
}
....
/* use strerror function to get the error message and write to log
or write to std error etc*/
The following man pages explain the error reporting in detail.
http://www.gnu.org/software/libc/manual/html_node/Error-Messages.html
http://man7.org/linux/man-pages/man3/errno.3.html
tutorialspoint.com is extremely terrible (at least when it comes to C) and as such must not be used. The standard resource to learn from is "The C Programming Language, 2nd edition" by Kernighan and Ritchie.
The preferred way to report stuff is to include the failing function in the message and use perror, e.g. perror("open")
EDIT: originally this did not include any justification for the claim about the site. I did not feel like it is necessary nor sensible. There is no write up I could link to either. They key was to avoid the site and everyone interested can easily conclude material in there is questionable at best and straight up wrong at worst.
However, since I got a weird backlash here are some excerpts:
http://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm
#include <stdio.h>
#include <stdlib.h>
Missing include for strcpy and strcat.
int main()
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
No need to cast malloc. Missing null-check. Why the 15?
strcpy(str, "tutorialspoint");
Bad error-inducing style. What if the length was to change? If an explicit allocation really needs to happen, strlen() + 1 can be used to get the needed size.
printf("String = %s, Address = %u\n", str, str);
'u' is an incorrect specifier for pointer type.
/* Reallocating memory */
str = (char *) realloc(str, 25);
Standard bad idiom. The code should use a temporary pointer to recover from error, or if recovery is not an option, exit.
strcat(str, ".com");
What's up with realloc from 15 to 25 just to add ".com"?
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
Does this justify my claim about the site?

How to use RegEx? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Doing regex in C# or PHP is very easy for me now. However currently I have a need to use regex in C. And, I don't seem to understand the usage of regcomp or regexec fully. It's definitely because of my lack of experience in C.
Use the PCRE library. Examples are included in the source, in the demo/ directory. Here's a direct link to pcredemo.c.
This may get you started, as you indicate regex(3) functions. Following is a trivial program matching its arguments. However, if you're relatively new to C, you'll want to go slowly with regex(3), as you'll be working with pointers and arrays and regmatch_t-supplied offsets and lions and tigers and bears. ;)
$ ./regexec '[[:digit:]]' 56789 alpha " " foo12bar
matched: 56789
matched: foo12bar
$ ./regexec '[[:digit:]](foo'
error: Unmatched ( or \(
$ ./regexec '['
error: Invalid regular expression
... and the source:
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
int main(int argc, char **argv) {
int r;
regex_t reg;
++argv; /* Danger! */
if (r = regcomp(&reg, *argv, REG_NOSUB|REG_EXTENDED)) {
char errbuf[1024];
regerror(r, &reg, errbuf, sizeof(errbuf));
printf("error: %s\n", errbuf);
return 1;
}
for (++argv; *argv; ++argv) {
if (regexec(&reg, *argv, 0, NULL, 0) == REG_NOMATCH)
continue;
printf("matched: %s\n", *argv);
}
return 0;
}
You need a library that provides it, and there are several to choose from. PCRE is one.
There's also libslack(str) - string module:
http://libslack.org/manpages/str.3.html
The gnu C library has a regex library

Resources