Write an argument to a string 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 2 months ago.
Improve this question
I am trying to write an argument to a string. What am I doing wrong?
How would it be more correct to write the argument from getopt to a string?
#include <string.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char fsrt[100], sstr[100], tstr[100];
int rez = 0;
while ( (rez = getopt(argc, argv, "f:s:l:")) != -1 )
{
if (rez == 'f') {
strcat(fsrt, optarg);
}
if (rez == 's') {
strcat(sstr, optarg);
}
if (rez == 'l') {
strcat(tstr, optarg);
}
}
printf("%s %s %s", fsrt, sstr, tstr);
return 0;
}
Update:
strange symbol in output.
./test -f one -s two -l three
output: https://i.stack.imgur.com/kksVh.png

char fsrt[100] = "", sstr[100]= "", tstr[100]= "";
If you don't initialize the char arrays they randomly point somewhere in memory.

Related

Why I got segmentation fault when using fgets in C? [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 2 years ago.
Improve this question
I run the program with this command:
./word_search oi < text.txt
and got segmentation fault when running it.
This program is aiming to find where the word (giving as command line arg) exists in a file and print out those lines.
#include <stdio.h>
#include "substring.c"
int main(int argc, char ** argv) {
if(argc == 2) {
char *str;
while(fgets(str, 100, stdin)) {
if(substring(str, argv[1]) != -1) {
printf("Found: %s", str);
}
}
}
return 0;
}
If I change char *str into char str[100] then it works pretty good. Could anyone please tell me why?
The contents in substring.c:
#include <stdio.h>
#include <string.h>
int substring(const char *line, const char *substr) {
int i, j;
int result;
for(i = 0; i <= strlen(line)-strlen(substr); i++) {
result = 0;
if(line[i] == substr[0]) {
int c = i;
for(j = 0; j < strlen(substr); j++) {
if (line[c] != substr[j]) {
result = -1;
}
c++;
}
if(result != -1)
return i;
}
}
return -1;
}
The contents in test.txt are just several lines of meaningless characters.
char *str is an unitialized pointer, it cannot hold the string you are trying to copy into it, either allocate memory to it:
#include <stdlib.h>
#define SIZE 100
char *str = malloc(SIZE); //char has the size of 1 across platforms
Or simply declare it with the size you need:
char str[SIZE];
Pass the size of str to fgets
while(fgets(str, SIZE, stdin))
Of fgets:
Your container will be null terminated, it can only hold a string of SIZE - 1 characters.
All characters above SIZE - 1, including '\n' will remain unread and therefore in the buffer, you might need to clear it.
I suggest you take some time to learn basic C. Especially read about pointers, they are bit hard to get right at first.
In your example, str is a pointer to an undefined memory location.

Run specific part of program from command line c [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 4 years ago.
Improve this question
I have a program that does two separate things. But I want to the program to only run one specific part based on what I enter in the command like in the format
program -a
program -s
where the a or s would be programmed to tell it to do something specific.
For example, if my program was something like:
# program -a entered
z = x + y
# program -s entered
z = x - y
Now I could easily do this with an if statement after running the program, but is it possible to directly skip to a statement like I said from the command prompt?
int main(int argc, char* argv[]) {
if (argc >= 2) {
if (strcmp(argv[1], "-a") == 0) {
z = x + y;
} else if (strcmp(argv[1], "-s") == 0) {
z = x - y;
}
}
return 0;
}
Determine if the value of argv[1] equal to "-a" or "-s"
You can use a switch statement on command-line arguments (in this case argv[1]).
argv[1] is a string containing the options you have given ("-a", "-s" etc).
But you have to perform certain checks for the validity of the command-line arguments before you can use them like this.
Check if argc == 2
Check if strlen(argv[1]) == 2
Check if argv[1][0] == '-'
An MCVE would look like this:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
if(argc == 2 && strlen(argv[1]) == 2 && argv[1][0] == '-')
{
switch(argv[1][1])
{
case 'a':
//do something
break;
case 's':
//do something else
break;
default:
//do the default thing
break;
}
}
else
{
//print appropriate error message
}
}

How to check if user did not enter all whitespace characters in C [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 6 years ago.
Improve this question
When prompting the user to enter there name, it is necessary that the user indeed entered a name and not just whitespace.
Output ex:
Name:
Your name is: /user entered only whitespace/
How would one validate that characters were actually implemented, and not just spaces? Im using fgets() to retreive my input however i am unable to post the code now for I am at work and doing this off my mobile device. If code is nessesary i will post what im working on late tonight (pacific standard time). Thank you!
One way to test is to check all characters if they are space.
#include <stdio.h>
#include <stdlib.h>
// TODO: you should use bool instead
int is_all_space(const char *s)
{
char *tmp;
tmp = (char *) s;
// you might check for '\n' instead in your case
// or even '\r'
while (*tmp != '\0') {
// TODO: this check will fail if the input has zero length
if (*tmp != ' ') {
return 0;
}
tmp++;
}
return 1;
}
// don't forget to put the argument in quotes if it contains spaces
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s somestring\n", argv[0]);
exit(EXIT_FAILURE);
}
if (is_all_space(argv[1])) {
puts("Input is all-space and nothing else");
} else {
puts("Input it not all-space");
}
exit(EXIT_SUCCESS);
}

Using a replace function in C programming [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 8 years ago.
Improve this question
How do I write a replace function which takes a pointer to a string as a parameter and replaces all spaces in that string with minus signs?
example :
input = "I love pies", output = "I-love-pies"
This is what you need:
#include <stdio.h>
int change_string(char *input) {
for (char *p = input; *p; p++) {
if (*p == ' ') *p = '-';
}
return 1;
}
int main() {
char input[] = "I love pies";
printf("%s\n", input);
change_string(input);
printf("%s\n", input);
return 0;
}

What is the name of the buffer that can be overflowed buf, msg, len or out [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to this and I can't seem to understand can you please help me identify the buffer that can be overflowed and why?
#include <stdio.h>
#include <string.h>
#define S 100
#define N 1000
int main(int argc, char *argv[]) {
char out[S];
char buf[N];
char msg[] = "Welcome to the argument echoing program\n";
int len = 0;
buf[0] = '\0';
printf(msg);
while (argc) {
sprintf(out, "argument %d is %s\n", argc-1, argv[argc-1]);
argc--;``
strncat(buf,out,sizeof(buf)-len-1);
len = strlen(buf);
}
printf("%s",buf);
return 0;
}
The problem is here:
sprintf(out, "argument %d is %s\n", argc - 1, argv[argc - 1]);
When you face a problem like this one, it's always a good idea to go through your code commenting lines until the program stops crashing. Then you will know where the bug is :D

Resources