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(®, *argv, REG_NOSUB|REG_EXTENDED)) {
char errbuf[1024];
regerror(r, ®, errbuf, sizeof(errbuf));
printf("error: %s\n", errbuf);
return 1;
}
for (++argv; *argv; ++argv) {
if (regexec(®, *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
Related
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.
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
I started learning C in university but only for one semester. I'm interested in learning a bit more about the language and started a small command line application.
I want to parse command line arguments. Since every command line application has to deal with this, I wonder if somebody has ever released a library to deal with that. Sure, I could do some decision making with if-else or switch statements, but I think it gets more complicated when I want to accept commands starting with '-' or '--' and also print a list of available commands, including descriptions.
Since I want to make my app for Windows and Linux, I can't use the GNU C Library which is posix-only (but has a helper for command handling).
Is there a nice way to achive tat or do I need to start from scratch?
The getopt will help you to parse the command line argument.
getopt :-
In getopt man page,
Syntax :
int getopt(int argc, char * const argv[], const char *optstring);
The getopt() function parses the command-line arguments. Its arguments argc and argv are the argument count and array as passed to the main() function on program invocation. An element of argv that starts with '-' (and is not exactly "-" or "--") is an option element. The characters of this element (aside from the initial '-') are option characters. If getopt() is called repeatedly, it returns successively each of the option characters from each of the option elements.
Example:-
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit(EXIT_SUCCESS);
}
Try the link for getopt(3) man page to read more about the getopt function.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
Hi all i'm at computer science (bd),for my exam project i want to make a c ocr program (no gui),i search in the internet for tesseract but i don't find any api for c but only for c++,anyone knows a ocr api for c language?
Thanks in advance
This is an example of using Tesseract C API, taken from the official documentation:
#include <stdio.h>
#include <allheaders.h>
#include <capi.h>
void die(const char *errstr) {
fputs(errstr, stderr);
exit(1);
}
int main(int argc, char *argv[]) {
TessBaseAPI *handle;
PIX *img;
char *text;
if((img = pixRead("img.png")) == NULL)
die("Error reading image\n");
handle = TessBaseAPICreate();
if(TessBaseAPIInit3(handle, NULL, "eng") != 0)
die("Error initialising tesseract\n");
TessBaseAPISetImage2(handle, img);
if(TessBaseAPIRecognize(handle, NULL) != 0)
die("Error in Tesseract recognition\n");
if((text = TessBaseAPIGetUTF8Text(handle)) == NULL)
die("Error getting text\n");
fputs(text, stdout);
TessDeleteText(text);
TessBaseAPIEnd(handle);
TessBaseAPIDelete(handle);
pixDestroy(&img);
return 0;
}
If you are using Linux, you can compile it as you would compile a program using C++ API.
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
So I have this bit of C code below. When I place printf statements to test the text from the input file, I see that I'm getting a bunch of junk values, to be more specific they are not even alphabetic or numerical, I think they are diamonds with question marks in them. I assume this means it is not processing these values the way it should be. The input file a bit of MIPS assembly code, but in this context it is only a text file. I have commented out all other parts of my program and am left with this small piece and yet I still receive the bad values. What could I possibly be doing wrong here?
The command I use to run the program on the console is:
./assembler -symbols adder.asm
Where ./assembler is the driver (argv[0])
-symbols is a tag used (argv[1])
adder.asm is the input file (argv[2])
So once opened I should be able to grab text out of this file, and it's not a problem with the file as far as I believe, it was working earlier.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
FILE *fp;
FILE *fp_out;
void main(int argc, char* argv[])
{
int mode;
if (strcmp(argv[1], "-symbols") == 0)
{
fp = fopen(argv[2], "r");
mode = 1;
}
else
{
fp = fopen(argv[1], "r");
fp_out = fopen(argv[2], "w");
mode = 2;
}
}
Try to add the following line right after the open section and add #include <errno.h> to the beginning.
printf("%p, %p, %d\n", fp, ftp_out, errno);
If the fp is null then there is some problem opening the file. If you do not check the return value, you can read from a wrong buffer. Maybe there is some permission problems (or whatever). Also if errno != 0 you have a problem. Check with perror <num> the errno value in command line (or see perror(3) function).