I am trying to send character pointers from rpc client to server in rpcgen for which below are the server and client programs
RPC program for RPC gen
struct clientinput {
char * optype;
char * word;
};
program DICTIONARY_PROG {
version DICTIONARY_VERS {
int USEDICTIONARY(clientinput) = 1;
} = 1;
} = 0x23451113;
RPC Server
#include "dictionary.h"
int *
usedictionary_1_svc(clientinput *argp, struct svc_req *rqstp)
{
static int result;
char *optype = (char*)malloc (10);
char *word = (char*)malloc (10);
char *a = argp->optype;
char *b = argp->word;
printf("Optype is %s\n", a);
printf("Word is %s\n", b);
printf("The optype is %s\n", strcpy(optype, argp->optype));
printf("The word is %s\n", strcpy(word, argp->word));
/*
* insert server code here
*/
return &result;
}
RPC Client
#include "dictionary.h"
void
dictionary_prog_1(char *host, char *optype, char *word)
{
CLIENT *clnt;
int *result_1;
clientinput usedictionary_1_arg;
//strcpy(usedictionary_1_arg.optype, optype);
//strcpy(usedictionary_1_arg.word, word);
usedictionary_1_arg.optype = optype;
usedictionary_1_arg.word = word;
printf("Optype input is %s\n",usedictionary_1_arg.optype);
printf("Word input is %s \n",usedictionary_1_arg.word);
#ifndef DEBUG
clnt = clnt_create (host, DICTIONARY_PROG, DICTIONARY_VERS, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */
result_1 = usedictionary_1(&usedictionary_1_arg, clnt);
if (result_1 == (int *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
clnt_destroy (clnt);
#endif /* DEBUG */
}
int
main (int argc, char *argv[])
{
char *host, *optype, *word;
if (argc < 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (1);
}
host = argv[1];
optype = argv[2];
word = argv[3];
dictionary_prog_1 (host,optype,word);
exit (0);
}
Here is the output on the server side
Optyep is a
Word is e
The optype is a
The word is e
The problem i encounter here is that only first character of the character pointers which I have passed from server to client gets printed. I have tried possible combinations of using character pointers and could not find the reason. So can someone please help me figure out the reason for this?
From looking at the documentation, RPCGen needs some help to distinguish between single character argument and actual array of characters since all parameters are passed as pointers. To let it know that you want an array of character, aka string, you need to use the string keyword in your struct declaration like so:
struct clientinput {
string optype<>;
string word<>;
};
This answer explains it as well and this blog post has a similar example to what you want to accomplish.
Related
I'm running a small rpc program/ using an rpc framework that takes a char[] from the client file and sends it to the server that enumerates the integers in the string.
I have a file client.c that takes user input and passes it to an external function in a header file.
#include <rpc/rpc.h>
#include "getNumInt.h"
int main(int argc, char **argv){
CLIENT *cli;
char *server;
server = argv[1];
cli = clnt_create(server, GETNUMINT, GNUMINT, "tcp"); //creates a client handle
/*does some check for whether the client connected*/
char command[256];
int *numInt;
fgets(command, 256, stdin);
numInt = enumints_1(&command, cli); //segfaults here according to backtrace
return(0);
}
The function enumints_1 is defined in my server stub server.c as:
int *enumints_1(msg, req)
char **msg; struct svc_req *req;{
printf(*msg);
static int numDigits = 0;
char msgcopy[256];
strcpy(msgcopy, *msg);
int i = 0;
for(i; i<strlen(msgcopy); i++){
if(msgcopy[i] >= '0' && msgcopy[i] <='9'){
numDigits++;
}
}
return(&numDigits);
}
My main issue is how I iterate through the char **msg as that is likely why my program is segfaulting.
command is just a string taken from user input and then passed by reference to the enumints_1 function.
Since it is a pointer to a point I assumed that I could just strcpy or memcpy to copy the string to a char array, but that doesn't work.
also my .x file:
struct intStringPair{
int numInts;
char msg[256];
};
program GETNUMINT{
version GNUMINT{
int ENUMINTS(string) = 1; //string considered char * the rpc generated file makes it so enumints_1 then has to take char **
int WRITEMESSAGE(intStringPair) = 2;
} = 1;
}= 0x20000001;
Like #user3386109 said:
command is not a pointer. So &command is not a pointer-to-a-pointer
so assigning &command to msg is not valid (and my compiler doesn't even compile it)
When I compile this code:
// my set up code
#include <stdio.h>
#include <string.h>
struct svc_req {};
typedef struct svc_req CLIENT;
struct svc_req *clnt_create(const char *, int, int, const char*) {return 0;}
int GETNUMINT=0, GNUMINT=0;
// your code verbatim
int *enumints_1(char **msg, struct svc_req *req){
printf(*msg);
static int numDigits = 0;
char msgcopy[256];
strcpy(msgcopy, *msg);
int i = 0;
for(i; i<strlen(msgcopy); i++){
if(msgcopy[i] >= '0' && msgcopy[i] <='9'){
numDigits++;
}
}
return(&numDigits);
}
int main(int argc, char **argv){
CLIENT *cli;
char *server;
server = argv[1];
cli = clnt_create(server, GETNUMINT, GNUMINT, "tcp"); //creates a client handle
/*does some check for whether the client connected*/
char command[256];
int *numInt;
fgets(command, 256, stdin);
numInt = enumints_1(&command, cli); //segfaults here according to backtrace
return(0);
}
The compiler says:
<source>: In function 'int main(int, char**)':
<source>:34:25: error: cannot convert 'char (*)[256]' to 'char**'
numInt = enumints_1(&command, cli); //segfaults here according to backtrace
^~~~~~~~
<source>:10:24: note: initializing argument 1 of 'int* enumints_1(char**, svc_req*)'
int *enumints_1(char **msg, struct svc_req *req){
~~~~~~~^~~
Compiler returned: 1
What you can do instead is make a pointer to the array and then pass the address of that:
// my set up code
#include <stdio.h>
#include <string.h>
struct svc_req {};
typedef struct svc_req CLIENT;
struct svc_req *clnt_create(const char *, int, int, const char*) {return 0;}
int GETNUMINT=0, GNUMINT=0;
// your code verbatim
int *enumints_1(char **msg, struct svc_req *req){
printf(*msg);
static int numDigits = 0;
char msgcopy[256];
strcpy(msgcopy, *msg);
int i = 0;
for(i; i<strlen(msgcopy); i++){
if(msgcopy[i] >= '0' && msgcopy[i] <='9'){
numDigits++;
}
}
return(&numDigits);
}
int main(int argc, char **argv){
CLIENT *cli;
char *server;
server = argv[1];
cli = clnt_create(server, GETNUMINT, GNUMINT, "tcp"); //creates a client handle
/*does some check for whether the client connected*/
char command[256], *command_pointer=command;
int *numInt;
fgets(command, 256, stdin);
numInt = enumints_1(&command_pointer, cli); //segfaults here according to backtrace
return(0);
}
I am creating a struct called Job and I want to create an array of struct Job. The name of my array is jobQueue I populate the array using commandline args. The instructor has it set up to where **args is being used. After the user inputs the name of the job and the execution time it gets added to the array. However, when I try to print jobQueue[0].name using the list() funct I have written, the name does not get printed. I'm trying to get my code set up to where I can print the name. I have provided a minimal version of my overall project that just focuses on the specific problem I am encountering and should compile and run fine.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <sys/wait.h>
#include <stdint.h>
#define EINVAL 1
#define E2BIG 2
#define MAXMENUARGS 7
//structure job initialize
struct Job {
//initializing name variable
char *name;
int executionTime;
};
//init the array
struct Job jobQueue[5] = {0};
//cmd function provided by intructor
int cmd_run(int nargs, char **args) {
int execT;
sscanf(args[2], "%d", &execT);
run(args[1], execT);
return 0;
}
//cmd function provided by intructor
void cmd_list() {
list();
}
//cmd function provided by intructor
static struct {
const char *name;
int (*func)(int nargs, char **args);
} cmdtable[] = {
/* commands: single command must end with \n */
{ "r", cmd_run},
{ "run", cmd_run},
{ "list\n", cmd_list}
};
//cmd function provided by intructor
//this is the function that handles the arguments entered by the user
//provided it just in case someone needs to see how arguments are being
//processed
int cmd_dispatch(char *cmd) {
time_t beforesecs, aftersecs, secs;
u_int32_t beforensecs, afternsecs, nsecs;
char *args[MAXMENUARGS];
int nargs = 0;
char *word;
char *context;
int i, result;
void *Dispatcher(void *arg);
for (word = strtok_r(cmd, " ", &context);
word != NULL;
word = strtok_r(NULL, " ", &context)) {
if (nargs >= MAXMENUARGS) {
printf("Command line has too many words\n");
return E2BIG;
}
args[nargs++] = word;
}
if (nargs == 0) {
return 0;
}
for (i = 0; cmdtable[i].name; i++) {
if (*cmdtable[i].name && !strcmp(args[0], cmdtable[i].name)) {
assert(cmdtable[i].func != NULL);
/* Call function through the cmd_table */
result = cmdtable[i].func(nargs, args);
return result;
}
}
printf("%s: Command not found\n", args[0]);
return EINVAL;
}
//adds job to the array using user arguments
void run(char name[], int executionTime) {
//creates a job using the arguments specified by user
struct Job job = {name, executionTime};
jobQueue[0] = job;
printf("\nJob added to queue now please type 'list'\n");
}
//name will not print here
void list() {
printf("\nSee how the name will not print below?\n");
char executionTimeStr[5];
for (int c = 0; c < sizeof (jobQueue) / sizeof (jobQueue[0]); c++) {
//prints job info formatted
if (jobQueue[c].name != NULL) {
sprintf(executionTimeStr, "%d", jobQueue[c].executionTime);
//job name will not print here, output is just left blank
printf("%s %20.8s", "Name", "ExecTime");
printf("%-10.15s %11.3s\n",
jobQueue[c].name,
executionTimeStr
);
}
}
}
int main(int argc, char *argv[]) {
printf("Welcome to our batch job scheduler\n");
printf("Please enter the following exactly: 'run job1 10' \n");
//ignore this, it handles my commandline parser
char *buffer;
size_t bufsize = 64;
buffer = (char*) malloc(bufsize * sizeof (char));
if (buffer == NULL) {
perror("Unable to malloc buffer");
exit(1);
}
while (1) {
printf("User Input: ");
getline(&buffer, &bufsize, stdin);
cmd_dispatch(buffer);
}
//ignore this, it handles my commandline parser
return 0;
}
I'm trying to be able to decode encoded strings that were encoded using a perl script. The reason I can't just change the perl script is because a lot of important data already exists that was saved via the perl script and it would be too much to decode in perl and recode another way. It's easier just to keep things in place (for now). However, the compiled perl code is 2MB. I want to write it in C so the executable will be a smaller size.
What I have so far is below. It won't work though. It basically gives me junk output. The problem I think is that the perl script used a hex-based encryption. How do I go about decoding that? Can someone point me to where I went wrong?
/*
Test to decode perl-encrypted string.
NOTE: Not all code written by me. Function code is either written by or derived
from code from other people in response to similar questions found on the
internet.
Required Lib: crypt (-lcrypt)
Perl Code from existing script (that is being converted to C):
use Crypt::CBC;
use Crypt::DES;
my $text = "thisisalongtest";
my $salt_key = "fOagmJOKu2SF";
my $cipher = Crypt::CBC->new( -key => $salt_key, -cipher => 'DES' -header => 'none');
my $enc_text = $cipher->encrypt_hex($text);
Perl crypt functions require libcrypt-cbc-perl & libcrypt-des-perl
Data:
Original Text: thisisalongtest
Salt Key: fOagmJOKu2SF
Resulting Encrypted String: 53616c7465645f5f167ebac84042fe7ceac836e1d3e7d3aa1dfc27e0e8cad0f1
Resulting output:
Decrypted: (unprintable junk characters)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <rpc/des_crypt.h>
#define BUFFSIZE 420
int encrypt(char key[9], char salt[9], char pass[BUFFSIZE], int mode);
void enc_from_hex(const char* st, char ret_result[BUFFSIZE]);
int hex_to_int(char c);
int hex_to_ascii(char c, char d);
int main (int argc, char *argv[]) {
int err;
char passwd[BUFFSIZE];
char result[BUFFSIZE];
char key[13];
sprintf(key,"fOagmJOKu2SF");
/* Change this from hex pairs to ASCII */
sprintf(passwd, "53616c7465645f5f167ebac84042fe7ceac836e1d3e7d3aa1dfc27e0e8cad0f1");
enc_from_hex(passwd, result);
/* Decrypt */
err = encrypt(key, "", result, 1); /* DO NOT use 'NULL' for 2nd parameter! */
if(err != 0) {
printf("Error.\n");
} else {
printf("Decrypted: %s\n", result);
}
return 0;
}
/* Encryption */
int encrypt(char key[13], char salt[13], char pass[BUFFSIZE], int mode){
char temp[13];
strcpy(temp, salt);
int buffsize;
int errcode;
des_setparity(key);
buffsize = strlen(pass);
/* Pad pass to ensure size is divisable by 8.*/
while (buffsize % 8 && buffsize<BUFFSIZE) {
pass[buffsize++] = '\0';
}
/* Determine Function */
if(mode == 1) {
errcode = cbc_crypt(key, pass, buffsize, DES_DECRYPT | DES_SW, temp);
} else {
errcode = cbc_crypt(key, pass, buffsize, DES_ENCRYPT | DES_SW, temp);
}
if (DES_FAILED(errcode) || strcmp(pass, "") == 0) {
return errcode;
}
return errcode;
}
/* Hex conversion functions */
void enc_from_hex(const char* st, char ret_result[BUFFSIZE]) {
char temp[2];
int length = strlen(st);
int i;
char buf = 0;
for(i = 0; i < length; i++) {
if(i % 2 != 0) {
sprintf(temp, "%c", hex_to_ascii(buf, st[i]));
strcat(ret_result, temp);
} else {
buf = st[i];
}
}
}
int hex_to_int(char c) {
int first = c / 16 - 3;
int second = c % 16;
int result = first*10 + second;
if(result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d) {
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
As #ikegami points out in the comments the value passed to key Crypt::CBC is not really a key. This value is passed to another function which combines it with a random salt then hashes it to generate the real key and initialization vector. The random salt is saved with the cypher text the idea being if you encrypt the same data with the same key more than once the output will be different every time.
If you convert your encrypted string to ascii you will notice the first eight characters spell Salted__, this corresponds to the format used by OpenSSL.
See below for a somewhat crude example using OpenSSL's EVP api:
//
// compile with: gcc -o crypt crypt.c -lssl -lcrypto
//
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
int main(int argc, char *argv[]){
char pass[]="fOagmJOKu2SF";
char text[]="53616c7465645f5f167ebac84042fe7ceac836e1d3e7d3aa1dfc27e0e8cad0f1";
int i = 0;
char *pos=text;
while(*pos){ // converts hex string to binary in place
sscanf(pos, "%2hhx", &text[i++]);
pos += 2;
} text[i]=0;
EVP_CIPHER_CTX ctx;
unsigned char key[8] = {0};
unsigned char iv[8] = {0};
int len;
char *clear = malloc(strlen(text));
// v-> First Charicter after 'Salted__'
EVP_BytesToKey(EVP_des_cbc(), EVP_md5(), &text[8], pass, strlen(pass), 1, key, iv);
EVP_DecryptInit(&ctx, EVP_des_cbc(), key, iv);
// v-> Cypertext starts after salt
EVP_DecryptUpdate(&ctx, clear, &len, &text[16], strlen(text)-15);
EVP_DecryptFinal(&ctx, clear, &len);
printf("%s\n", clear);
return 0;
}
http://www.ict.griffith.edu.au/anthony/info/crypto/openssl.hints
https://www.openssl.org/docs/manmaster/crypto/EVP_BytesToKey.html
https://www.openssl.org/docs/manmaster/crypto/EVP_EncryptInit.html
Hey, I've been working on this problem to read numbers from a text file and store them in an array but for some reason can't get it to work. Any help would be appreciated. the assignment is to implement the markov chain algorithm. I've made the reading part and assigning the array in the main fun() but i keep getting undeclared identifier as an error. Here is the code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "eprintf.h"
enum {
NPREF = 2, /* number of prefix words */
NHASH = 4093, /* size of state hash table array */
MAXGEN = 10000 /* maximum words generated */
};
typedef struct State State;
typedef struct Suffix Suffix;
struct State { /* prefix + suffix list */
char *pref[NPREF]; /* prefix words */
Suffix *suf; /* list of suffixes */
State *next; /* next in hash table */
};
struct Suffix { /* list of suffixes */
char *word; /* suffix */
Suffix *next; /* next in list of suffixes */
};
State *lookup(char *prefix[], int create);
void build(char *prefix[], FILE*);
void generate(int nwords);
void add(char *prefix[], char *word);
State *statetab[NHASH]; /* hash table of states */
char NONWORD[] = "\n"; /* cannot appear as real word */
//FILE* random_reader;
//FILE* myfile;
/* markov main: markov-chain random text generation */
int main(void)
{
int i, nwords = MAXGEN;
char *prefix[NPREF]; /* current input prefix */
FILE* random_reader;
FILE* myfile;
int c;
//long seed;
setprogname("markov");
//seed = time(NULL);
//srand(seed);
random_reader = fopen("../random_num.txt","r");
myfile = fopen("../alice30.txt","r");
int element;
int random_num[10000];
char line; //each number
int i=0;
while(fgets(line, 20, random_reader)!=NULL) // update the array
{
sscanf(line,"%o",&element);
random_num[i]=element;
i++;
}
for (i = 0; i < NPREF; i++) /* set up initial prefix */
prefix[i] = NONWORD;
build(prefix, stdin);
add(prefix, NONWORD);
generate(nwords);
return 0;
}
const int MULTIPLIER = 31; /* for hash() */
/* hash: compute hash value for array of NPREF strings */
unsigned int hash(char *s[NPREF])
{
unsigned int h;
unsigned char *p;
int i;
h = 0;
for (i = 0; i < NPREF; i++)
for (p = (unsigned char *) s[i]; *p != '\0'; p++)
h = MULTIPLIER * h + *p;
return h % NHASH;
}
/* lookup: search for prefix; create if requested. */
/* returns pointer if present or created; NULL if not. */
/* creation doesn't strdup so strings mustn't change later. */
State* lookup(char *prefix[NPREF], int create)
{
int i, h;
State *sp;
h = hash(prefix);
for (sp = statetab[h]; sp != NULL; sp = sp->next) {
for (i = 0; i < NPREF; i++)
if (strcmp(prefix[i], sp->pref[i]) != 0)
break;
if (i == NPREF) /* found it */
return sp;
}
if (create) {
sp = (State *) emalloc(sizeof(State));
for (i = 0; i < NPREF; i++)
sp->pref[i] = prefix[i];
sp->suf = NULL;
sp->next = statetab[h];
statetab[h] = sp;
}
return sp;
}
/* addsuffix: add to state. suffix must not change later */
void addsuffix(State *sp, char *suffix)
{
Suffix *suf;
suf = (Suffix *) emalloc(sizeof(Suffix));
suf->word = suffix;
suf->next = sp->suf;
sp->suf = suf;
}
/* add: add word to suffix list, update prefix */
void add(char *prefix[NPREF], char *suffix)
{
State *sp;
sp = lookup(prefix, 1); /* create if not found */
addsuffix(sp, suffix);
/* move the words down the prefix */
memmove(prefix, prefix+1, (NPREF-1)*sizeof(prefix[0]));
prefix[NPREF-1] = suffix;
}
/* build: read input, build prefix table */
void build(char *prefix[NPREF], FILE *f)
{
char buf[100], fmt[10];
/* create a format string; %s could overflow buf */
sprintf(fmt, "%%%ds", sizeof(buf)-1);
while (fscanf(f, fmt, buf) != EOF)
add(prefix, estrdup(buf));
}
/* generate: produce output, one word per line */
void generate(int nwords)
{
State *sp;
Suffix *suf;
char *prefix[NPREF], *w;
int i, nmatch;
for (i = 0; i < NPREF; i++) /* reset initial prefix */
prefix[i] = NONWORD;
for (i = 0; i < nwords; i++) {
sp = lookup(prefix, 0);
if (sp == NULL)
eprintf("internal error: lookup failed");
nmatch = 0;
for (suf = sp->suf; suf != NULL; suf = suf->next)
if (rand() % ++nmatch == 0) /* prob = 1/nmatch */
w = suf->word;
if (nmatch == 0)
eprintf("internal error: no suffix %d %s", i, prefix[0]);
if (strcmp(w, NONWORD) == 0)
break;
printf("%s\n", w);
memmove(prefix, prefix+1, (NPREF-1)*sizeof(prefix[0]));
prefix[NPREF-1] = w;
}
}
******* Here are the eprintf header file**************
/* eprintf.h: error wrapper functions */
extern void eprintf(char *, ...);
extern void weprintf(char *, ...);
extern char *estrdup(char *);
extern void *emalloc(size_t);
extern void *erealloc(void *, size_t);
extern char *progname(void);
extern void setprogname(char *);
#define NELEMS(a) (sizeof(a) / sizeof(a[0]))
*******here is the eprintf source file*********
#include <stdio.h>
#include <stdlib.h>
#include "eprintf.h"
#include <stdarg.h>
#include <string.h>
#include <errno.h>
static char *name = NULL; /* program name for messages */
/* eprintf: print error message and exit */
void eprintf(char *fmt, ...)
{
va_list args;
fflush(stdout);
if (progname() != NULL)
fprintf(stderr, "%s: ", progname());
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
fprintf(stderr, " %s", strerror(errno));
fprintf(stderr, "\n");
exit(2); /* conventional value for failed execution */
}
/* weprintf: print warning message */
void weprintf(char *fmt, ...)
{
va_list args;
fflush(stdout);
fprintf(stderr, "warning: ");
if (progname() != NULL)
fprintf(stderr, "%s: ", progname());
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
fprintf(stderr, " %s\n", strerror(errno));
else
fprintf(stderr, "\n");
}
/* emalloc: malloc and report if error */
void *emalloc(size_t n)
{
void *p;
p = malloc(n);
if (p == NULL)
eprintf("malloc of %u bytes failed:", n);
return p;
}
/* erealloc: realloc and report if error */
void *erealloc(void *vp, size_t n)
{
void *p;
p = realloc(vp, n);
if (p == NULL)
eprintf("realloc of %u bytes failed:", n);
return p;
}
/* estrdup: duplicate a string, report if error */
char *estrdup(char *s)
{
char *t;
t = (char *) malloc(strlen(s)+1);
if (t == NULL)
eprintf("estrdup(\"%.20s\") failed:", s);
strcpy(t, s);
return t;
}
/* progname: return stored name of program */
char *progname(void)
{
return name;
}
/* setprogname: set stored name of program */
void setprogname(char *str)
{
name = estrdup(str);
}
It is very important that you read compiler error message from the top down. You got 3 C2143 errors before you got the C2065 error. It is typical that error messages get less accurate and informative, an earlier error may produce a slew of additional errors. The first message complains about the element variable declaration. Then you get additional errors for any line that contains element since the compiler couldn't properly parse the declaration.
Your compiler requires you to put all variable declarations before the code that uses them.
Also note that you've got two declarations for the i variable. And that line needs to be an array of char: char line[20]; Moving the file reading code into a separate function would be a rather good idea.
In main() you have variable definitions appearing after code. This is permissible in C99 but not in C89, so if you're using an old C89 compiler, or something like MSVC which still doesn't support C99, then this is not going to compile. Move this block:
int element;
int random_num[10000];
char line; //each number
int i=0;
up above the code before it so that your variable definitions precede any actual code.
Im making an application that uses of API-threads in C, The program takes N-files (N>2) with names disordered,per each file is generated a thread of execution which sort the files using the function qsort, after being ordered files, each thread should create a file keeping the original file intact and displaying the sorted file to another file with the extension <.sorted>. The program sorts the numbers without problems, even if I put standard output displays the result on screen, but when I try to create the output file with extension .sorted the program breaks out.
this is my code file.c
#include <stdio.h> /* Standard buffered input/output */
#include <stdlib.h> /* Standard library functions */
#include <string.h> /* String operations */
#include <pthread.h> /* Thread related functions */
#include "pf1.h" /* Header specific to this app */
pthread_attr_t attr;
void *thread_worker(void *name_file)
{
FILE *entrada, *salida;
char* nombres = (char*)name_file;
int numero;
char temp [10000];
int i;
stats_t estadisticas;
printf ("File_name:%s\n", nombres);
entrada = fopen(nombres, "r");
salida = fopen (strcat(nombres, ".sorted"), "w");
while (!feof(entrada)){
fscanf (entrada, "%s\n",temp);
numero++;
}
char* lista[numero]; //array to sort the file
rewind (entrada);
for (i=0;i<numero;i++)
{
fscanf(entrada," %[^\n]", temp);
lista[i] = (char*)malloc((strlen(temp)+1)*sizeof(char));
strcpy(lista[i], temp);
}
size_t large = sizeof(lista) / sizeof(char *);
qsort(lista,large ,sizeof(char *) ,cstring_cmp );
printf ("Archivo Ordenado\n", i+1);
for (i=0;i<large;i++)
printf("%s\n",lista[i]);
pthread_exit(NULL);
}
int main(int argc, char *argv [])
{
stats_t **stats;
int i, rc;
pthread_t my_threads[argc-1];
pthread_attr_init(&attr);
if (argc <3) {
printf ("|files| > 2\n");
}else{
printf("files to sorted: %d\n", argc - 1);
for (i = 1; i < argc; i++){
//printf("%s%s\n", argv[i], (i < argc-1) ? " " : "");
rc = pthread_create(&my_threads[i], &attr, thread_worker, (void *)argv[i]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n",rc);
return -1;
}
}
}
return 0;
} /*end main */
this is mi file.h
#ifndef PF1_H_
#define PF1_H_
typedef struct _stats_t
{
char *longest, *shortest;
unsigned int numlines;
} stats_t;
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return -strcasecmp(*ia, *ib);
/* strcmp functions works exactly as expected from
comparison function */
}
void print_cstring_array(char **array, size_t len)
{
size_t i;
for(i=0; i<len; i++)
printf("%s | ", array[i]);
putchar('\n');
}
#endif /* PF1_1_H_ */
I would like some help with this problem because I can not see which is the fault ... thanks to all in advance and excuse my English
This line here may be your problem:
salida = fopen (strcat(nombres, ".sorted"), "w");
From what I can tell, that nombres variable is coming from argv. Since you're not the one allocating memory for argv, you don't know that there will be extra space for the ".sorted" (and there probably won't be). If you strcpy it to your own buffer with space for the ".sorted", you should be fine.
#define EXT_LEN 7
#define MAX_TOTAL_LEN 250
#define MAX_FILE_LEN 242 //MAX_TOTAL_LEN - EXT_LEN - 1
char *name_ptr;
char nombres[MAX_TOTAL_LEN];
int len;
name_ptr = (char*)name_file;
len = strlen(name_ptr);
if (len > MAX_FILE_LEN) {
len = MAX_FILE_LEN;
}
strncpy(nombres, name_ptr, len);
strcpy(nombres+len, ".sorted");
salida = fopen (nombres, "w");
I once had issues about not passing an int identifier while calling thread execution functions. Try building a struct with both an integer identifier and the filename, then pass it as a parameter to your thread_worker() function.