confusion while understanding parameters of main [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 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.

Related

Why is this giving me a segmentation fault 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 have a pretty simple program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// argc is amount of elements that the user inputs, check if 1234 isn't in code
if (strcmp(argv[argc-1],"1234" != 0)) {
exit(-1);
}
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i],"-h")) {
// do whatever
printf("Hello world!");
} else if (strcmp(argv[i],"-f")) {
// argv[i+1] will be the file, print out the file to console
}
}
}
It allows the user to enter something, say ./my_kill -h 1234. If 1234 isn't the last thing, it's supposed to just exit. Then in the for loop, if -h is used it prints hello world. For some reason it is giving me a segmentation fault and I don't understand why.
You have a parenthesis in the wrong position.
if (strcmp(argv[argc-1],"1234" != 0))
should be
if (strcmp(argv[argc-1],"1234") != 0)
Also, the first thing you should do is check if there is any information inside of argv.

I couldn't figure out what error is there in my code - segmentation fault core dumped error in C [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 3 years ago.
Improve this question
#include<stdio.h>
void main()
{
FILE *a[10];
int i,j,k;
float b[10][4][4];
for(i=0;i<8;i++)
{
char filename[100];
sprintf(filename,"infile%d.txt",i);
a[i]=fopen(filename,"r");
}
for(i=0;i<8;i++)
{
for(j=0;j<2;j++)
{
for (k=0;k<3;k++)
{
fscanf(a[i],"%f",&b[i][j][k]);
}
}
}
for (i=0;i<8;i++)
{
printf("\n-----------------%d--------------------",i);
for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
{
printf("\nb[%d][%d][%d]=%f",i,j,k,b[i][j][k]);
}
}
}
}
I have written the above code in C. Which just reads 8 different files and print it in terminal. The file name is infile0, infile1 and son on up to infile7. Though the code runs, it shows segmentation fault core dumped in the terminal. I couldn't figure out why this happens at all. Can some one help me figure out the mistake in the code.
Compiling with -g and running trough valgrind gives an error line 19 when no files are present.
Maybe you should add
if(!a[i])continue;
before scanf. (and set some message or default values).
also have a look at Input validation using scanf(), as you should check scanf return value.
I hope it helps, this my my first so contribution.
EDIT:
the -g flag is for your compiler, e.g
gcc -g myfile.c -o myfile
then run your binary trough valgrind.
It will tell you any problems with memory: leaks, invalid red/write...
valgrind ./myfile
Don't forget to install valgrind if it is not on your system.
A lot of remarks can be done from your code
1) In
void main()
main returns an int, not void, so must be
int main()
2) In
FILE *a[10];
..
for(i=0;i<8;i++)
{
...
a[i]=fopen(filename,"r");
why do you have an array with 10 entries to only use 8 of them ?, better to have
FILE *a[8];
3) 10 (becoming 8) is used a lot of times in your code, if you decide to change the number of elements you will have to change it every where, it is more simple to use a #define or sizeof(a)/sizeof(a[0])
4) In
char filename[100];
sprintf(filename,"infile%d.txt",i);
you are very generous with the needed size, even your int are in 64b and you increase so much the number of entries in a (no change to have enough stack nor file description anyway) 20 digits are enough for a positive number, so char filename[20+10+1]; is enough
5) In
float b[10][4][4];
...
for(j=0;j<2;j++)
{
for (k=0;k<3;k++)
like for 2) there is no reason to use a so large array if you do not use all the entries
6) In
fscanf(a[i],"%f",&b[i][j][k]);
you do not check if the corresponding file was open so if a[i] is not NULL, probably your segmentation fault comes because a file wasn't open
you do not detect the end of file nor if the file doesn't contain a valid float, you need to do for instance if (fscanf(a[i],"%f",&b[i][j][k]) != 1) { ...error management... }

How to read file in C programming using codeanywhere? [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 5 years ago.
Improve this question
here is the code given to me and a have also a text file where i need to get the Text from and compile the program.
You need to use open a file with fopen() first. But the current user needs to have perms to read/write the file.
We will use r to only read from a file. If the file is not read it will return NULL. You can fscanf() function to get the value of a file. The second parameter represents the type of the variable as in this case it's a string(char), third param is the mem address of the variable itself. Kind of like file version of scanf().
int main()
{
char a[1000];
FILE *myFile;
if ((myFile = fopen("C:\\myUSER\\newprogram.txt","r")) == NULL){
printf("Error! opening file");
exit(1);
}
fscanf(myFile ,"%s", &a);
printf("Value of a=%s", a);
fclose(myFile);
return 0;
}

Failed to Open source file while system call 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 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

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