Search Results

Search found 168 results on 7 pages for 'strcmp'.

Page 6/7 | < Previous Page | 2 3 4 5 6 7  | Next Page >

  • c++ code cons/pros

    - by VirusEcks
    below i have a code that runs in most of my simple programs .. . i want to know if it's good/bad ... and cons/pros . . win32 header file: win32.h #include <windows.h> #include <process.h> #include <stdarg.h> main header file: inc.h #include "win32.h" #ifndef INCS #define INCS #define DD #else #define DD extern #endif #ifndef VARS #define titlen L"my program" #endif DD wchar_t gtitle[512]; DD wchar_t gclass[512]; DD wchar_t gdir[32767]; #include "resources.h" #include "commonfunctions.h" then all files have something like this commonfunctions.h DD inline bool icmp( const char *String1, const char *String2 ) { if ( _stricmp( String1, String2 ) == 0 ) { return true; } return false; } DD inline bool scmp( const char *String1, const char *String2 ) { if ( strcmp( String1, String2 ) == 0 ) { return true; } return false; } all global variables have DD infront of them and all functions have DD too . is there a bad side of this ? . i came up with this idea and it wasn't problematic at all in small programs . but before i apply it in a large project will it be problematic ?. thanks in advance.

    Read the article

  • Redirect in codeigniter after login

    - by edelweiss
    Trying to do a redirect after a successful login. The login info is sent using ajax to the controller. My controller code as below public function login_controller_function() { $this->load->model('login_model'); if ($this->input->is_ajax_request()) { $user_name=$this->input->post('username'); $user_password = $this->input->post('password'); $this->load->helper('url'); $result = $this->login_model->verify_user($user_name,$user_password); // echo 'user_logged_in'; if(strcmp($result,'user_logged_in')==0) { redirect('welcome'); } } } But it is not working at all. Anyone knows whats wrong? Hi my html as requested. i am using twitter bootstrap as well <li class="divider-vertical"></li> <li><a href="#" id="login_btn">Login</a></li> <li><a href="<?php echo base_url('register'); ?>">Register</a></li> for the buttons so when i click the login button, a modal window will appear and ask for login info. so when i click on the login button, my js code will send an ajax request my js code as below /*Attempt register user jquery ajax*/ $('#login').click(function(){ var user_name = $('#loginHere').find('#user_name').val(); var user_password = $('#loginHere').find('#login_pwd').val(); if(user_name==""||user_password=="") return; var login_data = { username:user_name, password:user_password}; $.ajax({ type: "POST", dataType: "json", async: false, url:"login_register/login_controller_function", data: login_data, success: function(data) { if(data.login) { alert(data.redirect); window.location.replace(data.redirect); } else if(!data.login) { alert('data login not true'); } }, error:function(data){ alert('ajax error'); } }); }); });

    Read the article

  • Works for Short Input, Fails for Long Input. How to Solve?

    - by r0ach
    I've this program which finds substring in a string. It works for small inputs. But fails for long inputs. Here's the program: //Find Substring in given String #include <stdio.h> #include <string.h> main() { //Variable Initialization int i=0,j=0,k=0; char sentence[50],temp[50],search[50]; //Gets Strings printf("Enter Sentence: "); fgets(sentence,50,stdin); printf("Enter Search: "); fgets(search,50,stdin); //Actual Work Loop while(sentence[i]!='\0') { k=i;j=0; while(sentence[k]==search[j]) { temp[j]=sentence[k]; j++; k++; } if(strcmp(temp,search)==0) break; i++; } //Output Printing printf("Found string at: %d \n",k-strlen(search)); } Works for: Enter Sentence: good evening Enter Search: evening Found string at 6 Fails for: Enter Sentence: dear god please make this work Enter Search: make Found string at 25 Which is totally wrong. Can any expert find me a solution? P.S: This is kinda like reinventing the wheel since strstr() has this functionality. But I'm trying for a non-library way of doing it.

    Read the article

  • Template Syntax in C++

    - by Crystal
    I don't understand templates really and was trying to run a simple find the minimum for ints, doubles, chars. First question, why is template<typename T> sometimes used, and other times template<>? Second question, I do not know what I am doing wrong with the following code below: #include <iostream> template <typename T> T minimum(T arg1, T arg2) { return arg1 < arg2 ? arg1 : arg2; } template <typename T> // first I tried template <> instd of above, but wasn't sure the difference T minimum<const char *>(const char *arg1, const char *arg2) { return strcmp(arg1, arg2) ? arg2 : arg1; } int main() { std::cout << minimum<int>(4, 2) << '\n'; std::cout << minimum<double>(2.2, -56.7) << '\n'; std::cout << minimum(2.2, 2) << '\n'; } Compile Errors: error C2768: 'minimum' : illegal use of explicit template arguments error C2783: 'T minimum(const char *,const char *)' : could not deduce template argument for 'T' : see declaration of 'minimum' : error C2782: 'T minimum(T,T)' : template parameter 'T' is ambiguous : see declaration of 'minimum' Third, in getting familiar with separating .h and .cpp files, if I wanted this minimum() function to be a static function of my class, but it was the only function in that class, would I have to have a template class as well? I originally tried doing it that way instead of having it all in one file and I got some compile errors as well that I can't remember right now and was unsure how I would do that. Thanks!

    Read the article

  • Having trouble deleting a node from a linked list

    - by Requiem
    I've been working on this code for my shell that I'm creating and for some reason it isn't working. I'm implementing a watchuser function that watch's a user when an argument is given (args[1]). However, when a second argument (args[2]) of "off" is given, the user should be deleted from the linked list and should no longer be watched. struct userList * goList; goList = userInventory; do{ if (strcmp(userInventory->username, args[1]) == 0){ printf("%s\n", args[1]); printf("%s\n",userInventory->username); struct userList * temp2; temp2 = userInventory->next; if (userInventory->next != NULL){ userInventory->next = temp2->next; userInventory->next->prev = userInventory; } free(temp2); } goList = goList->next; }while (goList != userInventory); My global struct is also as follows: struct userList{ char * username; struct userList * prev; struct userList * next; } For reason, this code won't delete the user node from my linked list. The adding works, but this remove function won't and I'm not sure why. The print statements are there just to make sure it's executing the condition, which it is. If anyone could help me find the reasoning behind my error, I'd greatly appreciate it. Till then, I'll be trying to debug this. Thanks.

    Read the article

  • Nginx - basic http authentication on PHP-script

    - by half_bit
    I added a PHP-Script that serves as "cgi-bin", Configuration: location ~^/cgi-bin/.*\.(cgi|pl|py|rb) { gzip off; fastcgi_pass 127.0.0.1:9000; fastcgi_index cgi-bin.php; fastcgi_param SCRIPT_FILENAME /etc/nginx/cgi-bin.php; fastcgi_param SCRIPT_NAME /cgi-bin/cgi-bin.php; fastcgi_param X_SCRIPT_FILENAME /usr/lib/$fastcgi_script_name; fastcgi_param X_SCRIPT_NAME $fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_param REMOTE_USER $remote_user; } PHP-Script: <?php $descriptorspec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("pipe", "w") // stderr is a file to write to ); $newenv = $_SERVER; $newenv["SCRIPT_FILENAME"] = $_SERVER["X_SCRIPT_FILENAME"]; $newenv["SCRIPT_NAME"] = $_SERVER["X_SCRIPT_NAME"]; if (is_executable($_SERVER["X_SCRIPT_FILENAME"])) { $process = proc_open($_SERVER["X_SCRIPT_FILENAME"], $descriptorspec, $pipes, NULL, $newenv); if (is_resource($process)) { fclose($pipes[0]); $head = fgets($pipes[1]); while (strcmp($head, "\n")) { header($head); $head = fgets($pipes[1]); } fpassthru($pipes[1]); fclose($pipes[1]); fclose($pipes[2]); $return_value = proc_close($process); } else { header("Status: 500 Internal Server Error"); echo("Internal Server Error"); } } else { header("Status: 404 Page Not Found"); echo("Page Not Found"); } ?> The problem with it thought is that I cannot add basic authentication. As soon as I enable it for location ~/cgi-bin it gives me a 404 error when I try to look it up. How can I solve this? I thought about restricting access to only my second server where I then add basic authentication over a proxy, but there must be a simpler solution. Sorry for the bad title, I couldn't think of a better one.

    Read the article

  • Paypal IPN Handler for Cart

    - by kimmothy16
    Hey everyone! I'm using a Paypal add to cart button for a simple ecommerce website. I had a Paypal IPN handler written in PHP that was successfully working for 'Buy it Now' buttons and purchasing one item at a time. I would run a database query each time to update the store's inventory to reflect the purchase. Now I'm upgrading this store to a 'cart' version so people could check out with multiple items at a time. Would anyone be able to tell me, in general, how my IPN handler would need to be altered to accommodate this? I'm unsure of what a response from Paypal looks like for a cart purchase as opposed to a buy it now purchase. Thanks, any help or examples of working IPN cart scripts would be very appreciated! My current code is below.. // Paypal POSTs HTML FORM variables to this page // we must post all the variables back to paypal exactly unchanged and add an extra parameter cmd with value _notify-validate // initialise a variable with the requried cmd parameter $req = 'cmd=_notify-validate'; // go through each of the POSTed vars and add them to the variable foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } // post back to PayPal system to validate $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; // In a live application send it back to www.paypal.com // but during development you will want to uswe the paypal sandbox // comment out one of the following lines $fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30); //$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); // or use port 443 for an SSL connection //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { $item_name = stripslashes($_POST['item_name']); $item_number = $_POST['item_number']; $item_id = $_POST['custom']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; //full amount of payment. payment_gross in US $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; //unique transaction id $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; $size = $_POST['option_selection1']; $item_id = $_POST['item_id']; $business = $_POST['business']; if ($payment_status == 'Completed') { // UPDATE THE DATABASE }

    Read the article

  • Problems with this stack implementation

    - by Andersson Melo
    where is the mistake? My code here: typedef struct _box { char *dados; struct _box * proximo; } Box; typedef struct _pilha { Box * topo; }Stack; void Push(Stack *p, char * algo) { Box *caixa; if (!p) { exit(1); } caixa = (Box *) calloc(1, sizeof(Box)); caixa->dados = algo; caixa->proximo = p->topo; p->topo = caixa; } char * Pop(Stack *p) { Box *novo_topo; char * dados; if (!p) { exit(1); } if (p->topo==NULL) return NULL; novo_topo = p->topo->proximo; dados = p->topo->dados; free(p->topo); p->topo = novo_topo; return dados; } void StackDestroy(Stack *p) { char * c; if (!p) { exit(1); } c = NULL; while ((c = Pop(p)) != NULL) { free(c); } free(p); } int main() { int conjunto = 1; char p[30]; int flag = 0; Stack *pilha = (Stack *) calloc(1, sizeof(Stack)); FILE* arquivoIN = fopen("L1Q3.in","r"); FILE* arquivoOUT = fopen("L1Q3.out","w"); if (arquivoIN == NULL) { printf("Erro na leitura do arquivo!\n\n"); exit(1); } fprintf(arquivoOUT,"Conjunto #%d\n",conjunto); while (fscanf(arquivoIN,"%s", p) != EOF ) { if (pilha->topo == NULL && flag != 0) { conjunto++; fprintf(arquivoOUT,"\nConjunto #%d\n",conjunto); } if(strcmp(p, "return") != 0) { Push(pilha, p); } else { p = Pop(pilha); if(p != NULL) { fprintf(arquivoOUT, "%s\n", p); } } flag = 1; } StackDestroy(pilha); return 0; } The Pop function returns the string value read from file. But is not correct and i don't know why.

    Read the article

  • conversion of DNA to Protein - c structure issue

    - by sam
    I am working on conversion of DNA sequence to Protein sequence. I had completed all program only one error I found there is of structure. dna_codon is a structure and I am iterating over it.In first iteration it shows proper values of structure but from next iteration, it dont show the proper value stored in structure. Its a small error so do not think that I havnt done anything and downvote. I am stucked here because I am new in c for structures. CODE : #include <stdio.h> #include<string.h> void main() { int i, len; char short_codons[20]; char short_slc[1000]; char sequence[1000]; struct codons { char amino_acid[20], slc[20], dna_codon[40]; }; struct codons c1 [20]= { {"Isoleucine", "I", "ATT, ATC, ATA"}, {"Leucine", "L", "CTT, CTC, CTA, CTG, TTA, TTG"}, {"Valine", "V", "GTT, GTC, GTA, GTG"}, {"Phenylalanine", "F", "TTT, TTC"}, {"Methionine", "M", "ATG"}, {"Cysteine", "C", "TGT, TGC"}, {"Alanine", "A", "GCT, GCC, GCA, GCG"}, {"Proline", "P", "CCT, CCC, CCA,CCG "}, {"Threonine", "T", "ACT, ACC, ACA, ACG"}, {"Serine", "S", "TCT, TCC, TCA, TCG, AGT, AGC"}, {"Tyrosine", "Y", "TAT, TAC"}, {"Tryptophan", "W", "TGG"}, {"Glutamine", "Q", "CAA, CAG"}, {"Aspargine","N" "AAT, AAC"}, {"Histidine", "H", "CAT, CAC"}, {"Glutamic acid", "E", "GAA, GAG"}, {"Aspartic acid", "D", "GAT, GAC"}, {"Lysine", "K", "AAA, AAG"}, {"Arginine", "R", "CGT, CGC, CGA, CGG, AGA, AGG"}, {"Stop codons", "Stop", "AA, TAG, TGA"} }; int count = 0; printf("Enter the sequence: "); gets(sequence); char *input_string = sequence; char *tmp_str = input_string; int k; char *pch; while (*input_string != '\0') { char string_3l[4] = {'\0'}; strncpy(string_3l, input_string, 3); printf("\n-----------%s & %s----------", string_3l, tmp_str ); for(k=0;k<20;k++) { //printf("@REAL - %s", c1[0].dna_codon); printf("@ %s", c1[k].dna_codon); int x; x = c1[k].dna_codon; pch = strtok(x, ","); while (pch != NULL) { printf("\n%d : %s with %s", k, string_3l, pch); count=strcmp(string_3l, pch); if(count==0) { strcat(short_slc, c1[k].slc); printf("\n==>%s", short_slc); } pch = strtok (NULL, " ,.-"); } } input_string = input_string+3; } printf("\nProtien sequence is : %s\n", short_slc); } INPUT : TAGTAG OUTPUT : If you see output of printf("\n-----------%s & %s----------", string_3l, tmp_str ); in both iterations, we found that values defined in structure are reduced. I want to know why structure reduces it or its my mistake? because I am stucked here

    Read the article

  • Sening a file from memory (rather than disk) over HTTP using libcurl

    - by cinek1lol
    Hi! I would like to send pictures via a program written in C + +. - OK WinExec("C:\\curl\\curl.exe -H Expect: -F \"fileupload=@C:\\curl\\ok.jpg\" -F \"xml=yes\" -# \"http://www.imageshack.us/index.php\" -o data.txt -A \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\" -e \"http://www.imageshack.us\"", NULL); It works, but I would like to send the pictures from pre-loaded carrier to a variable char (you know what I mean? First off, I load the pictures into a variable and then send the variable), cause now I have to specify the path of the picture on a disk. I wanted to write this program in c++ by using the curl library, not through exe. extension. I have also found such a program (which has been modified by me a bit) #include <stdio.h> #include <string.h> #include <iostream> #include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; static const char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "send", CURLFORM_FILE, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "nowy.jpg", CURLFORM_COPYCONTENTS, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); curl = curl_easy_init(); headerlist = curl_slist_append(headerlist, buf); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.imageshack.us/index.php"); if ( (argc == 2) && (!strcmp(argv[1], "xml=yes")) ) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_formfree(formpost); curl_slist_free_all (headerlist); } system("pause"); return 0; }

    Read the article

  • how I can overcome this error C2679: binary '>>' : no operator found which takes a right-hand oper

    - by hussein abdullah
    #include <iostream> using std::cout; using std::cin; using std::endl; #include <cstring> void initialize(char[],int*); void input(const char[] ,int&); void print ( const char*,const int); void growOlder (const char [], int* ); bool comparePeople(const char* ,const int*,const char*,const int*); int main(){ char name1[25]; char name2[25]; int age1; int age2; initialize (name1,&age1); initialize (name2,&age2); print(name1,age1); print(name2,age2); input(name1,age1); input(name2,age2); print(name1,age1); print(name2,age2); growOlder(name2,&age2); if(comparePeople(name1,&age1,name2,&age2)) cout<<"Both People have the same name and age "<<endl; return 0; } void input(const char name[],int &age) { cout<<"Enter a name :"; cin>>name ; cout<<"Enter an age:"; cin>>age; cout<<endl; } void initialize ( char name[],int *age) { name[0]='\0'; *age=0; } void print ( const char name[],const int age ) { cout<<"The Value stored in variable name is :" <<name<<endl <<"The Value stored in variable age is :" <<age<<endl<<endl; } void growOlder(const char name[],int *age) { cout<< name <<" has grown one year older\n\n"; *age++; } bool comparePeople (const char *name1,const int *age1, const char *name2,const int *age2) { return(*age1==*age2 && !strcmp(name1,name2)); }

    Read the article

  • how to solve the errors of this program

    - by hussein abdullah
    include using std::cout; using std::cin; using std::endl; include void initialize(char[],int*); void input(const char[] ,int&); void print ( const char*,const int); void growOlder (const char [], int* ); bool comparePeople(const char* ,const int*,const char*,const int*); int main(){ char name1[25]; char name2[25]; int age1; int age2; initialize (name1,&age1); initialize (name2,&age2); print(name1,*age1); print(name2,*age2); input(name1,age1); input(name2,age2); print(&name1,&age1); print(&name2,&age2); growOlder(name2,age2); if(comparePeople(name1,&age1,name2,&age2)) cout<<"Both People have the same name and age "<<endl; return 0; } void input(const char name[],int &age) { cout<<"Enter a name :"; cinname ; cout<<"Enter an age:"; cin>>age; cout<<endl; } void initialize ( char name[],int *age) { name=""; age=0; } void print ( const char name[],const int age ) { cout<<"The Value stored in variable name is :" < void growOlder(const char name[],int *age) { cout<< name <<" has grown one year older\n\n"; *age++; } bool comparePeople (const char *name1,const int *age1, const char *name2,const int *age2) { return(age1==age2 &&strcmp(name1,name2)); }

    Read the article

  • Can't find mistake -- 'segmentation fault' - in C

    - by Mosh
    Hello all! I wrote this function but can't get on the problem that gives me 'segmentation fault' msg. Thank you for any help guys !! /*This function extract all header files in a *.c1 file*/ void includes_extractor(FILE *c1_fp, char *c1_file_name ,int c1_file_str_len ) { int i=0; FILE *c2_fp , *header_fp; char ch, *c2_file_name,header_name[80]; /* we can assume line length 80 chars MAX*/ char inc_name[]="include"; char inc_chk[INCLUDE_LEN+1]; /*INCLUDE_LEN is defined | +1 for null*/ /* making the c2 file name */ c2_file_name=(char *) malloc ((c1_file_str_len)*sizeof(char)); if (c2_file_name == NULL) { printf("Out of memory !\n"); exit(0); } strcpy(c2_file_name , c1_file_name); c2_file_name[c1_file_str_len-1] = '\0'; c2_file_name[c1_file_str_len-2] = '2'; /*Open source & destination files + ERR check */ if( !(c1_fp = fopen (c1_file_name,"r") ) ) { fprintf(stderr,"\ncannot open *.c1 file !\n"); exit(0); } if( !(c2_fp = fopen (c2_file_name,"w+") ) ) { fprintf(stderr,"\ncannot open *.c2 file !\n"); exit(0); } /*next code lines are copy char by char from c1 to c2, but if meet header file, copy its content */ ch=fgetc(c1_fp); while (!feof(c1_fp)) { i=0; /*zero i */ if (ch == '#') /*potential #include case*/ { fgets(inc_chk, INCLUDE_LEN+1, c1_fp); /*8 places for "include" + null*/ if(strcmp(inc_chk,inc_name)==0) /*case #include*/ { ch=fgetc(c1_fp); while(ch==' ') /* stop when head with a '<' or '"' */ { ch=fgetc(c1_fp); } /*while(2)*/ ch=fgetc(c1_fp); /*start read header file name*/ while((ch!='"') || (ch!='>')) /*until we get the end of header name*/ { header_name[i] = ch; i++; ch=fgetc(c1_fp); }/*while(3)*/ header_name[i]='\0'; /*close the header_name array*/ if( !(header_fp = fopen (header_name,"r") ) ) /*open *.h for read + ERR chk*/ { fprintf(stderr,"cannot open header file !\n"); exit(0); } while (!feof(header_fp)) /*copy header file content to *.c2 file*/ { ch=fgetc(header_fp); fputc(ch,c2_fp); }/*while(4)*/ fclose(header_fp); } }/*frst if*/ else { fputc(ch,c2_fp); } ch=fgetc(c1_fp); }/*while(1)*/ fclose(c1_fp); fclose(c2_fp); free (c2_file_name); }

    Read the article

  • [c++] upload image to imageshack

    - by cinek1lol
    Hi! I would like to send pictures via a program written in C + +. - OK WinExec("C:\\curl\\curl.exe -H Expect: -F \"fileupload=@C:\\curl\\ok.jpg\" -F \"xml=yes\" -# \"http://www.imageshack.us/index.php\" -o data.txt -A \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\" -e \"http://www.imageshack.us\"", NULL); It works, but I would like to send the pictures from pre-loaded carrier to a variable char (you know what I mean? First off, I load the pictures into a variable and then send the variable), cause now I have to specify the path of the picture on a disk. I wanted to write this program in c++ by using the curl library, not through exe. extension. I have also found such a program (which has been modified by me a bit) #include <stdio.h> #include <string.h> #include <iostream> #include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; static const char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "send", CURLFORM_FILE, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "nowy.jpg", CURLFORM_COPYCONTENTS, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); curl = curl_easy_init(); headerlist = curl_slist_append(headerlist, buf); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.imageshack.us/index.php"); if ( (argc == 2) && (!strcmp(argv[1], "xml=yes")) ) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_formfree(formpost); curl_slist_free_all (headerlist); } system("pause"); return 0; }

    Read the article

  • How to check for local Wi-Fi (not just cellular connection) using iPhone SDK?

    - by Michael
    I'm currently using the following to check whether Wi-Fi is available for my application: #import <SystemConfiguration/SystemConfiguration.h> static inline BOOL addressReachable(const struct sockaddr_in *hostAddress); BOOL localWiFiAvailable() { struct sockaddr_in localWifiAddress; bzero(&localWifiAddress, sizeof(localWifiAddress)); localWifiAddress.sin_len = sizeof(localWifiAddress); localWifiAddress.sin_family = AF_INET; // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); return addressReachable(&localWifiAddress); } static inline BOOL addressReachable(const struct sockaddr_in *hostAddress) { const SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)hostAddress); if (target != NULL) { SCNetworkReachabilityFlags flags = 0; const BOOL reachable = SCNetworkReachabilityGetFlags(target, &flags); CFRelease(target); return reachable && (flags & kSCNetworkFlagsReachable); } return NO; } This, however, does not return NO as it should when the iPhone is connected only to a cellular network but not a Wi-Fi network. Does anyone know how to fix this? Edit So this is what I ended up using: #import <arpa/inet.h> // For AF_INET, etc. #import <ifaddrs.h> // For getifaddrs() #import <net/if.h> // For IFF_LOOPBACK BOOL localWiFiAvailable() { struct ifaddrs *addresses; struct ifaddrs *cursor; BOOL wiFiAvailable = NO; if (getifaddrs(&addresses) != 0) return NO; cursor = addresses; while (cursor != NULL) { if (cursor -> ifa_addr -> sa_family == AF_INET && !(cursor -> ifa_flags & IFF_LOOPBACK)) // Ignore the loopback address { // Check for WiFi adapter if (strcmp(cursor -> ifa_name, "en0") == 0) { wiFiAvailable = YES; break; } } cursor = cursor -> ifa_next; } freeifaddrs(addresses); return wiFiAvailable; } Thanks "unforgiven" (and Matt Brown apparently).

    Read the article

  • [c++] upload image to imageshack

    - by cinek1lol
    Hi. I would like to send pictures via a program written in C + + I wrote such a thing using curl.exe WinExec("C:\\curl\\curl.exe -H Expect: -F \"fileupload=@C:\\curl\\ok.jpg\" -F \"xml=yes\" -# \"http://www.imageshack.us/index.php\" -o data.txt -A \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\" -e \"http://www.imageshack.us\"", NULL); This only works that I would like to send pictures to a variable pre-loaded char (you know what I mean? first reads the pictures into a variable and then send that variable), because now I have to specify the path to the images on disk I wanted to make this program was written in C + + using the curl library, and not the exe. I found it such a program (which some have modified) #include <stdio.h> #include <string.h> #include <iostream> #include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; static const char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "send", CURLFORM_FILE, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "nowy.jpg", CURLFORM_COPYCONTENTS, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); curl = curl_easy_init(); headerlist = curl_slist_append(headerlist, buf); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.imageshack.us/index.php"); if ( (argc == 2) && (!strcmp(argv[1], "xml=yes")) ) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_formfree(formpost); curl_slist_free_all (headerlist); } system("pause"); return 0; } I will be grateful for any help

    Read the article

  • What is user gcc's purpose in requesting code possibly like this?

    - by James Morris
    In the question between syntax, are there any equal function the user gcc is requesting only what I can imagine to be the following code: #include <stdio.h> #include <string.h> /* estimated magic values */ #define MAXFUNCS 8 #define MAXFUNCLEN 3 int the_mainp_compare_func(char** mainp) { char mainp0[MAXFUNCS][MAXFUNCLEN] = { 0 }; char mainp1[MAXFUNCS][MAXFUNCLEN] = { 0 }; char* psrc, *pdst; int i = 0; int func = 0; psrc = mainp[0]; printf("scanning mainp[0] for functions...\n"); while(*psrc) { if (*psrc == '\0') break; else if (*psrc == ',') ++psrc; else { mainp0[func][0] = *psrc++; if (*psrc == ',') { mainp0[func][1] = '\0'; psrc++; } else if (*psrc !='\0') { mainp0[func][1] = *psrc++; mainp0[func][2] = '\0'; } printf("function: '%s'\n", mainp0[func]); } ++func; } printf("\nscanning mainp[1] for functions...\n"); psrc = mainp[1]; func = 0; while(*psrc) { if (*psrc == '\0') break; else if (*psrc == ',') ++psrc; else { mainp1[func][0] = *psrc++; if (*psrc == ',') { mainp1[func][1] = '\0'; psrc++; } else if (*psrc !='\0') { mainp1[func][1] = *psrc++; mainp1[func][2] = '\0'; } printf("function: '%s'\n", mainp1[func]); } ++func; } printf("\ncomparing functions in '%s' with those in '%s'\n", mainp[0], mainp[1] ); int func2; func = 0; while (*mainp0[func] != '\0') { func2 = 0; while(*mainp1[func2] != '\0') { printf("comparing %s with %s\n", mainp0[func], mainp1[func2]); if (strcmp(mainp0[func], mainp1[func2++]) == 0) return 1; /* not sure what to return here */ } ++func; } /* no matches == failure */ return -1; /* not sure what to return on failure */ } int main(int argc, char** argv) { char* mainp[] = { "P,-Q,Q,-R", "R,A,P,B,F" }; if (the_mainp_compare_func(mainp) == 1) printf("a match was found, but I don't know what to do with it!\n"); else printf("no match found, and I'm none the wiser!\n"); return 0; } My question is, what is it's purpose?

    Read the article

  • C++: incorrect swapping of nodes in linked list

    - by Dragon
    I have 2 simple structures: struct Address { char city[255]; }; typedef Address* AddressPtr; struct Person { char fullName[255]; Address* address; Person* next; }; typedef Person* PersonPtr; The Person structure forms the Linked list where new elements are added to the beginning of the list. What I want to do is to sort them by fullName. At first I tried to swap links, but I lost the beginning of the list and as a result my list was sorted partially. Then I decided to sort list by swapping the values of nodes. But I get strange results. For a list with names: Test3, Test2, Test1, I get Test3, Test3, Test3. Here is my sorting code: void sortByName(PersonPtr& head) { TaskPtr currentNode, nextNode; for(currentNode = head; currentNode->next != NULL; currentNode = currentNode->next) { for(nextNode = currentNode->next; nextNode != NULL; nextNode = nextNode->next) { if(strcmp(currentNode->fullName, nextNode->fullName) > 0) { swapNodes(currentNode, nextNode); } } } } void swapNodes(PersonPtr& node1, PersonPtr& node2) { PersonPtr temp_node = node2; strcpy(node2->fullName, node1->fullName); strcpy(node1->fullName, temp_node->fullName); strcpy(node2->address->city, node1->address->city); strcpy(node1->address->city, temp_node->address->city); } After the sorting completion, nodes values are a little bit strange. UPDATED This is how I swapped links void swapNodes(PersonPtr& node1, PersonPtr& node2) { PersonPtr temp_person; AddressPtr temp_address; temp_person = node2; node2 = node1; node1 = temp_person; temp_address = node2->address; node2->address = node1->address; node1->address = temp_address; }

    Read the article

  • Returning and printing string array index in C

    - by user1781966
    I've got a function that searches through a list of names and I'm trying to get the search function to return the index of the array back to the main function and print out the starting location of the name found. Everything I've tried up to this point either crashes the program or results in strange output. Here is my search function: #include<stdio.h> #include<conio.h> #include<string.h> #define MAX_NAMELENGTH 10 #define MAX_NAMES 5 void initialize(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys, int i); int search(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys); int main() { char names[MAX_NAMES][MAX_NAMELENGTH]; int i, Number_entrys,search_result,x; printf("How many names would you like to enter to the list?\n"); scanf("%d",&Number_entrys); initialize(names,Number_entrys,i); search_result= search(names,Number_entrys); if (search_result==-1){ printf("Found no names.\n"); }else { printf("%s",search_result); } getch(); return 0; } void initialize(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys,int i) { if(Number_entrys>MAX_NAMES){ printf("Please choose a smaller entry\n"); }else{ for (i=0; i<Number_entrys;i++){ scanf("%s",names[i]); } } } int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys) { int x; char new_name[MAX_NAMELENGTH]; printf("Now enter a name in which you would like to search the list for\n"); scanf("%s",new_name); for(x = 0; x < Number_entrys; x++) { if ( strcmp( new_name, names[x] ) == 0 ) { return x; } } return -1; } Like I mentioned before I have tried a lot of different ways to try and fix this issue, but I cant seem to get them to work. Printing X like what I have above is just the last thing I tried, and therefor know that it doesn't work. Any suggestions on the simplest way to do this?

    Read the article

  • Telephone Directory

    - by Mizukage of Meron 5
    I need your help. We are ask to make a telephone directory program that asks your name, address, and telephone number. If the name you entered already exists, it will display that it already exists. This is what i have so far... #include<stdio.h> #include<conio.h> struct file { char name[25],address[25]; double telno; }; char tempname[25],tempadd[25]; double tempnum; int x; int choice; FILE *fp; main() { struct file rec; clrscr(); fp=fopen("TelDir.txt","a+"); while(!feof(fp)) { fscanf(fp,"%s %s %.0lf,&tempname,&tempadd,&tempnum); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); printf("\nEnter Name: "); gets(rec.name); if(strcmp(rec.name,tempname)==1) { printf("\n\nALREADY EXIST!"); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); getch(); } else { printf("Enter Address: "); scanf("%s",&rec.address); printf("Enter your Telephone No.: "); scanf("%lf",&rec.telno); printf("%s\t\t%s\t\t%\t\t0lf",rec.name,rec.address,rec.telno); fprintf(fp,"%s %s %.0lf\n",rec.name,rec.address,rec.telno); } } fclose(fp); getch(); } But this thing doesn't work. I don't know where the error is. Can someone help me on this? I would really appreciate if you could help me somehow.

    Read the article

  • Sending a file from memory (rather than disk) over HTTP using libcurl

    - by cinek1lol
    Hi! I would like to send pictures via a program written in C + +. - OK WinExec("C:\\curl\\curl.exe -H Expect: -F \"fileupload=@C:\\curl\\ok.jpg\" -F \"xml=yes\" -# \"http://www.imageshack.us/index.php\" -o data.txt -A \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\" -e \"http://www.imageshack.us\"", NULL); It works, but I would like to send the pictures from pre-loaded carrier to a variable char (you know what I mean? First off, I load the pictures into a variable and then send the variable), cause now I have to specify the path of the picture on a disk. I wanted to write this program in c++ by using the curl library, not through exe. extension. I have also found such a program (which has been modified by me a bit) #include <stdio.h> #include <string.h> #include <iostream> #include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; static const char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "send", CURLFORM_FILE, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "nowy.jpg", CURLFORM_COPYCONTENTS, "nowy.jpg", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); curl = curl_easy_init(); headerlist = curl_slist_append(headerlist, buf); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.imageshack.us/index.php"); if ( (argc == 2) && (!strcmp(argv[1], "xml=yes")) ) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_formfree(formpost); curl_slist_free_all (headerlist); } system("pause"); return 0; }

    Read the article

  • C#/.NET Little Wonders: Comparer&lt;T&gt;.Default

    - by James Michael Hare
    I’ve been working with a wonderful team on a major release where I work, which has had the side-effect of occupying most of my spare time preparing, testing, and monitoring.  However, I do have this Little Wonder tidbit to offer today. Introduction The IComparable<T> interface is great for implementing a natural order for a data type.  It’s a very simple interface with a single method: 1: public interface IComparer<in T> 2: { 3: // Compare two instances of same type. 4: int Compare(T x, T y); 5: }  So what do we expect for the integer return value?  It’s a pseudo-relative measure of the ordering of x and y, which returns an integer value in much the same way C++ returns an integer result from the strcmp() c-style string comparison function: If x == y, returns 0. If x > y, returns > 0 (often +1, but not guaranteed) If x < y, returns < 0 (often –1, but not guaranteed) Notice that the comparison operator used to evaluate against zero should be the same comparison operator you’d use as the comparison operator between x and y.  That is, if you want to see if x > y you’d see if the result > 0. The Problem: Comparing With null Can Be Messy This gets tricky though when you have null arguments.  According to the MSDN, a null value should be considered equal to a null value, and a null value should be less than a non-null value.  So taking this into account we’d expect this instead: If x == y (or both null), return 0. If x > y (or y only is null), return > 0. If x < y (or x only is null), return < 0. But here’s the problem – if x is null, what happens when we attempt to call CompareTo() off of x? 1: // what happens if x is null? 2: x.CompareTo(y); It’s pretty obvious we’ll get a NullReferenceException here.  Now, we could guard against this before calling CompareTo(): 1: int result; 2:  3: // first check to see if lhs is null. 4: if (x == null) 5: { 6: // if lhs null, check rhs to decide on return value. 7: if (y == null) 8: { 9: result = 0; 10: } 11: else 12: { 13: result = -1; 14: } 15: } 16: else 17: { 18: // CompareTo() should handle a null y correctly and return > 0 if so. 19: result = x.CompareTo(y); 20: } Of course, we could shorten this with the ternary operator (?:), but even then it’s ugly repetitive code: 1: int result = (x == null) 2: ? ((y == null) ? 0 : -1) 3: : x.CompareTo(y); Fortunately, the null issues can be cleaned up by drafting in an external Comparer.  The Soltuion: Comparer<T>.Default You can always develop your own instance of IComparer<T> for the job of comparing two items of the same type.  The nice thing about a IComparer is its is independent of the things you are comparing, so this makes it great for comparing in an alternative order to the natural order of items, or when one or both of the items may be null. 1: public class NullableIntComparer : IComparer<int?> 2: { 3: public int Compare(int? x, int? y) 4: { 5: return (x == null) 6: ? ((y == null) ? 0 : -1) 7: : x.Value.CompareTo(y); 8: } 9: }  Now, if you want a custom sort -- especially on large-grained objects with different possible sort fields -- this is the best option you have.  But if you just want to take advantage of the natural ordering of the type, there is an easier way.  If the type you want to compare already implements IComparable<T> or if the type is System.Nullable<T> where T implements IComparable, there is a class in the System.Collections.Generic namespace called Comparer<T> which exposes a property called Default that will create a singleton that represents the default comparer for items of that type.  For example: 1: // compares integers 2: var intComparer = Comparer<int>.Default; 3:  4: // compares DateTime values 5: var dateTimeComparer = Comparer<DateTime>.Default; 6:  7: // compares nullable doubles using the null rules! 8: var nullableDoubleComparer = Comparer<double?>.Default;  This helps you avoid having to remember the messy null logic and makes it to compare objects where you don’t know if one or more of the values is null. This works especially well when creating say an IComparer<T> implementation for a large-grained class that may or may not contain a field.  For example, let’s say you want to create a sorting comparer for a stock open price, but if the market the stock is trading in hasn’t opened yet, the open price will be null.  We could handle this (assuming a reasonable Quote definition) like: 1: public class Quote 2: { 3: // the opening price of the symbol quoted 4: public double? Open { get; set; } 5:  6: // ticker symbol 7: public string Symbol { get; set; } 8:  9: // etc. 10: } 11:  12: public class OpenPriceQuoteComparer : IComparer<Quote> 13: { 14: // Compares two quotes by opening price 15: public int Compare(Quote x, Quote y) 16: { 17: return Comparer<double?>.Default.Compare(x.Open, y.Open); 18: } 19: } Summary Defining a custom comparer is often needed for non-natural ordering or defining alternative orderings, but when you just want to compare two items that are IComparable<T> and account for null behavior, you can use the Comparer<T>.Default comparer generator and you’ll never have to worry about correct null value sorting again.     Technorati Tags: C#,.NET,Little Wonders,BlackRabbitCoder,IComparable,Comparer

    Read the article

  • socket operation on nonsocket or bad file descriptor

    - by Magn3s1um
    I'm writing a pthread server which takes requests from clients and sends them back a bunch of .ppm files. Everything seems to go well, but sometimes when I have just 1 client connected, when trying to read from the file descriptor (for the file), it says Bad file Descriptor. This doesn't make sense, since my int fd isn't -1, and the file most certainly exists. Other times, I get this "Socket operation on nonsocket" error. This is weird because other times, it doesn't give me this error and everything works fine. When trying to connect multiple clients, for some reason, it will only send correctly to one, and then the other client gets the bad file descriptor or "nonsocket" error, even though both threads are processing the same messages and do the same routines. Anyone have an idea why? Here's the code that is giving me that error: while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); The messages for both threads are the same, being of the form ./path/imageXX.ppm where XX is the number that should go to the client. The file size of each image is 58368 bytes. Sometimes, this code hangs on the read, and stops execution. I don't know this would be either, because the file descriptor comes back as valid. Thanks in advanced. Edit: Here's some sample output: Sending to client a: ./support/images/sw90.ppm This is fd 4 Error: : Socket operation on non-socket Sending to client a: ./support/images/sw91.ppm This is fd 4 Error: : Socket operation on non-socket Sending ./support/images/sw92.ppm This is fd 4 I am hhere2 Error: : Socket operation on non-socket My dispatcher has defeated evil Sample with 2 clients (client b was serviced first) Sending to client b: ./support/images/sw87.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw88.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw89.ppm This is fd 6 Error: : Success This is fd 6 Error: : Bad file descriptor Sending to client a: ./support/images/sw85.ppm This is fd 6 Error: As you can see, who ever is serviced first in this instance can open the files, but not the 2nd person. Edit2: Full code. Sorry, its pretty long and terribly formatted. #include <netinet/in.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "ring.h" /* Version 1 Here is what is implemented so far: The threads are created from the arguments specified (number of threads that is) The server will lock and update variables based on how many clients are in the system and such. The socket that is opened when a new client connects, must be passed to the threads. To do this, we need some sort of global array. I did this by specifying an int client and main_pool_busy, and two pointers poolsockets and nonpoolsockets. My thinking on this was that when a new client enters the system, the server thread increments the variable client. When a thread is finished with this client (after it sends it the data), the thread will decrement client and close the socket. HTTP servers act this way sometimes (they terminate the socket as soon as one transmission is sent). *Note down at bottom After the server portion increments the client counter, we must open up a new socket (denoted by new_sd) and get this value to the appropriate thread. To do this, I created global array poolsockets, which will hold all the socket descriptors for our pooled threads. The server portion gets the new socket descriptor, and places the value in the first spot of the array that has a 0. We only place a value in this array IF: 1. The variable main_pool_busy < worknum (If we have more clients in the system than in our pool, it doesn't mean we should always create a new thread. At the end of this, the server signals on the condition variable clientin that a new client has arrived. In our pooled thread, we then must walk this array and check the array until we hit our first non-zero value. This is the socket we will give to that thread. The thread then changes the array to have a zero here. What if our all threads in our pool our busy? If this is the case, then we will know it because our threads in this pool will increment main_pool_busy by one when they are working on a request and decrement it when they are done. If main_pool_busy >= worknum, then we must dynamically create a new thread. Then, we must realloc the size of our nonpoolsockets array by 1 int. We then add the new socket descriptor to our pool. Here's what we need to figure out: NOTE* Each worker should generate 100 messages which specify the worker thread ID, client socket descriptor and a copy of the client message. Additionally, each message should include a message number, starting from 0 and incrementing for each subsequent message sent to the same client. I don't know how to keep track of how many messages were to the same client. Maybe we shouldn't close the socket descriptor, but rather keep an array of structs for each socket that includes how many messages they have been sent. Then, the server adds the struct, the threads remove it, then the threads add it back once they've serviced one request (unless the count is 100). ------------------------------------------------------------- CHANGES Version 1 ---------- NONE: this is the first version. */ #define MAXSLOTS 30 #define dis_m 15 //problems with dis_m ==1 //Function prototypes void inc_clients(); void init_mutex_stuff(pthread_t*, pthread_t*); void *threadpool(void *); void server(int); void add_to_socket_pool(int); void inc_busy(); void dec_busy(); void *dispatcher(); void create_message(long, int, int, char *, char *); void init_ring(); void add_to_ring(char *, char *, int, int, int); int socket_from_string(char *); void add_to_head(char *); void add_to_tail(char *); struct message * reorder(struct message *, struct message *, int); int get_threadid(char *); void delete_socket_messages(int); struct message * merge(struct message *, struct message *, int); int get_request(char *, char *, char*); ///////////////////// //Global mutexes and condition variables pthread_mutex_t startservice; pthread_mutex_t numclients; pthread_mutex_t pool_sockets; pthread_mutex_t nonpool_sockets; pthread_mutex_t m_pool_busy; pthread_mutex_t slots; pthread_mutex_t numm; pthread_mutex_t circ; pthread_cond_t clientin; pthread_cond_t m; /////////////////////////////////////// //Global variables int clients; int main_pool_busy; int * poolsockets, nonpoolsockets; int worknum; struct ring mqueue; /////////////////////////////////////// int main(int argc, char ** argv){ //error handling if not enough arguments to program if(argc != 3){ printf("Not enough arguments to server: ./server portnum NumThreadsinPool\n"); _exit(-1); } //Convert arguments from strings to integer values int port = atoi(argv[1]); worknum = atoi(argv[2]); //Start server portion server(port); } /////////////////////////////////////////////////////////////////////////////////////////////// //The listen server thread///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void server(int port){ int sd, new_sd; struct sockaddr_in name, cli_name; int sock_opt_val = 1; int cli_len; pthread_t threads[worknum]; //create our pthread id array pthread_t dis[1]; //create our dispatcher array (necessary to create thread) init_mutex_stuff(threads, dis); //initialize mutexes and stuff //Server setup /////////////////////////////////////////////////////// if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror("(servConn): socket() error"); _exit (-1); } if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char *) &sock_opt_val, sizeof(sock_opt_val)) < 0) { perror ("(servConn): Failed to set SO_REUSEADDR on INET socket"); _exit (-1); } name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl(INADDR_ANY); if (bind (sd, (struct sockaddr *)&name, sizeof(name)) < 0) { perror ("(servConn): bind() error"); _exit (-1); } listen (sd, 5); //End of server Setup ////////////////////////////////////////////////// for (;;) { cli_len = sizeof (cli_name); new_sd = accept (sd, (struct sockaddr *) &cli_name, &cli_len); printf ("Assigning new socket descriptor: %d\n", new_sd); inc_clients(); //New client has come in, increment clients add_to_socket_pool(new_sd); //Add client to the pool of sockets if (new_sd < 0) { perror ("(servConn): accept() error"); _exit (-1); } } pthread_exit(NULL); //Quit } //Adds the new socket to the array designated for pthreads in the pool void add_to_socket_pool(int socket){ pthread_mutex_lock(&m_pool_busy); //Lock so that we can check main_pool_busy int i; //If not all our main pool is busy, then allocate to one of them if(main_pool_busy < worknum){ pthread_mutex_unlock(&m_pool_busy); //unlock busy, we no longer need to hold it pthread_mutex_lock(&pool_sockets); //Lock the socket pool array so that we can edit it without worry for(i = 0; i < worknum; i++){ //Find a poolsocket that is -1; then we should put the real socket there. This value will be changed back to -1 when the thread grabs the sockfd if(poolsockets[i] == -1){ poolsockets[i] = socket; pthread_mutex_unlock(&pool_sockets); //unlock our pool array, we don't need it anymore inc_busy(); //Incrememnt busy (locks the mutex itself) pthread_cond_signal(&clientin); //Signal first thread waiting on a client that a client needs to be serviced break; } } } else{ //Dynamic thread creation goes here pthread_mutex_unlock(&m_pool_busy); } } //Increments the client number. If client number goes over worknum, we must dynamically create new pthreads void inc_clients(){ pthread_mutex_lock(&numclients); clients++; pthread_mutex_unlock(&numclients); } //Increments busy void inc_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy++; pthread_mutex_unlock(&m_pool_busy); } //Initialize all of our mutexes at the beginning and create our pthreads void init_mutex_stuff(pthread_t * threads, pthread_t * dis){ pthread_mutex_init(&startservice, NULL); pthread_mutex_init(&numclients, NULL); pthread_mutex_init(&pool_sockets, NULL); pthread_mutex_init(&nonpool_sockets, NULL); pthread_mutex_init(&m_pool_busy, NULL); pthread_mutex_init(&circ, NULL); pthread_cond_init (&clientin, NULL); main_pool_busy = 0; poolsockets = malloc(sizeof(int)*worknum); int threadreturn; //error checking variables long i = 0; //Loop and create pthreads for(i; i < worknum; i++){ threadreturn = pthread_create(&threads[i], NULL, threadpool, (void *) i); poolsockets[i] = -1; if(threadreturn){ perror("Thread pool created unsuccessfully"); _exit(-1); } } pthread_create(&dis[0], NULL, dispatcher, NULL); } ////////////////////////////////////////////////////////////////////////////////////////// /////////Main pool routines ///////////////////////////////////////////////////////////////////////////////////////// void dec_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy--; pthread_mutex_unlock(&m_pool_busy); } void dec_clients(){ pthread_mutex_lock(&numclients); clients--; pthread_mutex_unlock(&numclients); } //This is what our threadpool pthreads will be running. void *threadpool(void * threadid){ long id = (long) threadid; //Id of this thread int i; int socket; int counter = 0; //Try and gain access to the next client that comes in and wait until server signals that a client as arrived while(1){ pthread_mutex_lock(&startservice); //lock start service (required for cond wait) pthread_cond_wait(&clientin, &startservice); //wait for signal from server that client exists pthread_mutex_unlock(&startservice); //unlock mutex. pthread_mutex_lock(&pool_sockets); //Lock the pool socket so we can get the socket fd unhindered/interrupted for(i = 0; i < worknum; i++){ if(poolsockets[i] != -1){ socket = poolsockets[i]; poolsockets[i] = -1; pthread_mutex_unlock(&pool_sockets); } } printf("Thread #%d is past getting the socket\n", id); int incoming = 1; while(counter < 100 && incoming != 0){ char buffer[512]; bzero(buffer,512); int startcounter = 0; incoming = read(socket, buffer, 512); if(buffer[0] != 0){ //client ID:priority:request:arguments char id[100]; long prior; char request[100]; char arg1[100]; char message[100]; char arg2[100]; char * point; point = strtok(buffer, ":"); strcpy(id, point); point = strtok(NULL, ":"); prior = atoi(point); point = strtok(NULL, ":"); strcpy(request, point); point = strtok(NULL, ":"); strcpy(arg1, point); point = strtok(NULL, ":"); if(point != NULL){ strcpy(arg2, point); } int fd; if(strcmp(request, "start_movie") == 0){ int count = 1; while(count <= 100){ char temp[10]; snprintf(temp, 50, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s to %s\n", message, id); count++; add_to_ring(message, id, prior, counter, socket); //Adds our created message to the ring counter++; } printf("I'm out of the loop\n"); } else if(strcmp(request, "seek_movie") == 0){ int count = atoi(arg2); while(count <= 100){ char temp[10]; snprintf(temp, 10, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s\n", message); count++; } } //create_message(id, socket, counter, buffer, message); //Creates our message from the input from the client. Stores it in buffer } else{ delete_socket_messages(socket); break; } } counter = 0; close(socket);//Zero out counter again } dec_clients(); //client serviced, decrement clients dec_busy(); //thread finished, decrement busy } //Creates a message void create_message(long threadid, int socket, int counter, char * buffer, char * message){ snprintf(message, strlen(buffer)+15, "%d:%d:%d:%s", threadid, socket, counter, buffer); } //Gets the socket from the message string (maybe I should just pass in the socket to another method) int socket_from_string(char * message){ char * substr1 = strstr(message, ":"); char * substr2 = substr1; substr2++; int occurance = strcspn(substr2, ":"); char sock[10]; strncpy(sock, substr2, occurance); return atoi(sock); } //Adds message to our ring buffer's head void add_to_head(char * message){ printf("Adding to head of ring\n"); mqueue.head->message = malloc(strlen(message)+1); //Allocate space for message strcpy(mqueue.head->message, message); //copy bytes into allocated space } //Adds our message to our ring buffer's tail void add_to_tail(char * message){ printf("Adding to tail of ring\n"); mqueue.tail->message = malloc(strlen(message)+1); //allocate space for message strcpy(mqueue.tail->message, message); //copy bytes into allocated space mqueue.tail->next = malloc(sizeof(struct message)); //allocate space for the next message struct } //Adds a message to our ring void add_to_ring(char * message, char * id, int prior, int mnum, int socket){ //printf("This is message %s:" , message); pthread_mutex_lock(&circ); //Lock the ring buffer pthread_mutex_lock(&numm); //Lock the message count (will need this to make sure we can't fill the buffer over the max slots) if(mqueue.head->message == NULL){ add_to_head(message); //Adds it to head mqueue.head->socket = socket; //Set message socket mqueue.head->priority = prior; //Set its priority (thread id) mqueue.head->mnum = mnum; //Set its message number (used for sorting) mqueue.head->id = malloc(sizeof(id)); strcpy(mqueue.head->id, id); } else if(mqueue.tail->message == NULL){ //This is the problem for dis_m 1 I'm pretty sure add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } else{ mqueue.tail->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.tail->next; add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } mqueue.mcount++; pthread_mutex_unlock(&circ); if(mqueue.mcount >= dis_m){ pthread_mutex_unlock(&numm); pthread_cond_signal(&m); } else{ pthread_mutex_unlock(&numm); } printf("out of add to ring\n"); fflush(stdout); } ////////////////////////////////// //Dispatcher routines ///////////////////////////////// void *dispatcher(){ init_ring(); while(1){ pthread_mutex_lock(&slots); pthread_cond_wait(&m, &slots); pthread_mutex_lock(&numm); pthread_mutex_lock(&circ); printf("Dispatcher to the rescue!\n"); mqueue.head = reorder(mqueue.head, mqueue.tail, mqueue.mcount); //printf("This is the head %s\n", mqueue.head->message); //printf("This is the tail %s\n", mqueue.head->message); fflush(stdout); struct message * pointer = mqueue.head; int count = 0; while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); printf("My dispatcher has defeated evil\n"); } } void init_ring(){ mqueue.head = malloc(sizeof(struct message)); mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.mcount = 0; } struct message * reorder(struct message * begin, struct message * end, int num){ //printf("I am reordering for size %d\n", num); fflush(stdout); int i; if(num == 1){ //printf("Begin: %s\n", begin->message); begin->next = NULL; return begin; } else{ struct message * left = begin; struct message * right; int middle = num/2; for(i = 1; i < middle; i++){ left = left->next; } right = left -> next; left -> next = NULL; //printf("Begin: %s\nLeft: %s\nright: %s\nend:%s\n", begin->message, left->message, right->message, end->message); left = reorder(begin, left, middle); if(num%2 != 0){ right = reorder(right, end, middle+1); } else{ right = reorder(right, end, middle); } return merge(left, right, num); } } struct message * merge(struct message * left, struct message * right, int num){ //printf("I am merginging! left: %s %d, right: %s %dnum: %d\n", left->message,left->priority, right->message, right->priority, num); struct message * start, * point; int lenL= 0; int lenR = 0; int flagL = 0; int flagR = 0; int count = 0; int middle1 = num/2; int middle2; if(num%2 != 0){ middle2 = middle1+1; } else{ middle2 = middle1; } while(lenL < middle1 && lenR < middle2){ count++; //printf("In here for count %d\n", count); if(lenL == 0 && lenR == 0){ if(left->priority < right->priority){ start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ start = right; point = right; right = right->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ ////printf("This is where we are\n"); start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ start = right; point = right; right = right->next; point->next = NULL; lenR++; } } } else{ if(left->priority < right->priority){ point->next = left; left = left->next; //move the left pointer point = point->next; point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ point->next = left; //set our enum; left = left->next; point = point->next;//move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } } } if(lenL == middle1){ flagL = 1; break; } if(lenR == middle2){ flagR = 1; break; } } if(flagL == 1){ point->next = right; point = point->next; for(lenR; lenR< middle2-1; lenR++){ point = point->next; } point->next = NULL; mqueue.tail = point; } else{ point->next = left; point = point->next; for(lenL; lenL< middle1-1; lenL++){ point = point->next; } point->next = NULL; mqueue.tail = point; } //printf("This is the start %s\n", start->message); //printf("This is mqueue.tail %s\n", mqueue.tail->message); return start; } void delete_socket_messages(int a){ }

    Read the article

  • 42 passed to TerminateProcess, sometimes GetExitCodeProcess returns 0

    - by Emil
    After I get a handle returned by CreateProcess, I call TerminateProcess, passing 42 for the process exit code. Then, I use WaitForSingleObject for the process to terminate, and finally I call GetExitCodeProcess. None of the function calls report errors. The child process is an infinite loop and does not terminate on its own. The problem is that sometimes GetExitCodeProcess returns 42 for the exit code (as it should) and sometimes it returns 0. Any idea why? #include <string> #include <sstream> #include <iostream> #include <assert.h> #include <windows.h> void check_call( bool result, char const * call ); #define CHECK_CALL(call) check_call(call,#call); int main( int argc, char const * argv[] ) { if( argc>1 ) { assert( !strcmp(argv[1],"inf") ); for(;;) { } } int err=0; for( int i=0; i!=200; ++i ) { STARTUPINFO sinfo; ZeroMemory(&sinfo,sizeof(STARTUPINFO)); sinfo.cb=sizeof(STARTUPINFO); PROCESS_INFORMATION pe; char cmd_line[32768]; strcat(strcpy(cmd_line,argv[0])," inf"); CHECK_CALL((CreateProcess(0,cmd_line,0,0,TRUE,0,0,0,&sinfo,&pe)!=0)); CHECK_CALL((CloseHandle(pe.hThread)!=0)); CHECK_CALL((TerminateProcess(pe.hProcess,42)!=0)); CHECK_CALL((WaitForSingleObject(pe.hProcess,INFINITE)==WAIT_OBJECT_0)); DWORD ec=0; CHECK_CALL((GetExitCodeProcess(pe.hProcess,&ec)!=0)); CHECK_CALL((CloseHandle(pe.hProcess)!=0)); err += (ec!=42); } std::cout << err; return 0; } std::string get_last_error_str( DWORD err ) { std::ostringstream s; s << err; LPVOID lpMsgBuf=0; if( FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, 0) ) { assert(lpMsgBuf!=0); std::string msg; try { std::string((LPCSTR)lpMsgBuf).swap(msg); } catch( ... ) { } LocalFree(lpMsgBuf); if( !msg.empty() && msg[msg.size()-1]=='\n' ) msg.resize(msg.size()-1); if( !msg.empty() && msg[msg.size()-1]=='\r' ) msg.resize(msg.size()-1); s << ", \"" << msg << '"'; } return s.str(); } void check_call( bool result, char const * call ) { assert(call && *call); if( !result ) { std::cerr << call << " failed.\nGetLastError:" << get_last_error_str(GetLastError()) << std::endl; exit(2); } }

    Read the article

  • How do I maximize code coverage?

    - by naivedeveloper
    Hey all, the following is a snippet of code taken from the unix ptx utility. I'm attempting to maximize code coverage on this utility, but I am unable to reach the indicated portion of code. Admittedly, I'm not as strong in my C skills as I used to be. The portion of code is indicated with comments, but it is towards the bottom of the block. if (used_length == allocated_length) { allocated_length += (1 << SWALLOW_REALLOC_LOG); block->start = (char *) xrealloc (block->start, allocated_length); } Any help interpreting the indicated portion in order to cover that block would be greatly appreciated. /* Reallocation step when swallowing non regular files. The value is not the actual reallocation step, but its base two logarithm. */ #define SWALLOW_REALLOC_LOG 12 static void swallow_file_in_memory (const char *file_name, BLOCK *block) { int file_handle; /* file descriptor number */ struct stat stat_block; /* stat block for file */ size_t allocated_length; /* allocated length of memory buffer */ size_t used_length; /* used length in memory buffer */ int read_length; /* number of character gotten on last read */ /* As special cases, a file name which is NULL or "-" indicates standard input, which is already opened. In all other cases, open the file from its name. */ bool using_stdin = !file_name || !*file_name || strcmp (file_name, "-") == 0; if (using_stdin) file_handle = STDIN_FILENO; else if ((file_handle = open (file_name, O_RDONLY)) < 0) error (EXIT_FAILURE, errno, "%s", file_name); /* If the file is a plain, regular file, allocate the memory buffer all at once and swallow the file in one blow. In other cases, read the file repeatedly in smaller chunks until we have it all, reallocating memory once in a while, as we go. */ if (fstat (file_handle, &stat_block) < 0) error (EXIT_FAILURE, errno, "%s", file_name); if (S_ISREG (stat_block.st_mode)) { size_t in_memory_size; block->start = (char *) xmalloc ((size_t) stat_block.st_size); if ((in_memory_size = read (file_handle, block->start, (size_t) stat_block.st_size)) != stat_block.st_size) { error (EXIT_FAILURE, errno, "%s", file_name); } block->end = block->start + in_memory_size; } else { block->start = (char *) xmalloc ((size_t) 1 << SWALLOW_REALLOC_LOG); used_length = 0; allocated_length = (1 << SWALLOW_REALLOC_LOG); while (read_length = read (file_handle, block->start + used_length, allocated_length - used_length), read_length > 0) { used_length += read_length; /* Cannot cover from this point...*/ if (used_length == allocated_length) { allocated_length += (1 << SWALLOW_REALLOC_LOG); block->start = (char *) xrealloc (block->start, allocated_length); } /* ...to this point. */ } if (read_length < 0) error (EXIT_FAILURE, errno, "%s", file_name); block->end = block->start + used_length; } /* Close the file, but only if it was not the standard input. */ if (! using_stdin && close (file_handle) != 0) error (EXIT_FAILURE, errno, "%s", file_name); }

    Read the article

< Previous Page | 2 3 4 5 6 7  | Next Page >