Search Results

Search found 451 results on 19 pages for 'fp'.

Page 2/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • write 2d array to a file in C (Operating system)

    - by Bobj-C
    Hello All, I used to use the code below to Write an 1D array to a File: FILE *fp; float floatValue[5] = { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F }; int i; if((fp=fopen("test", "wb"))==NULL) { printf("Cannot open file.\n"); } if(fwrite(floatValue, sizeof(float), 5, fp) != 5) printf("File read error."); fclose(fp); /* read the values */ if((fp=fopen("test", "rb"))==NULL) { printf("Cannot open file.\n"); } if(fread(floatValue, sizeof(float), 5, fp) != 5) { if(feof(fp)) printf("Premature end of file."); else printf("File read error."); } fclose(fp); for(i=0; i<5; i++) printf("%f ", floatValue[i]); My question is if i want to write and read 2D array ??

    Read the article

  • jQuery nextUntill id < num or alternative

    - by Volmar
    Hi, i'm using jQuery to show/hide different LI-elements based on their classes. Look at this example. <li id="1" class="fp de1"></li> <li id="2" class="fp de1"><button onclick="hide(2,2);"></li> <li id="3" class="fp de2"><button onclick="hide(3,3);"></li> <li id="4" class="fp de3"><button onclick="hide(4,4);"></li> <li id="5" class="fp de4"></li> <li id="6" class="fp de3"></li> <li id="7" class="fp de3"></li> <li id="8" class="fp de1"><button onclick="hide(8,2);"></li> <li id="9" class="fp de2"><button onclick="hide(9,3);"></li> <li id="10" class="fp de3"><button onclick="hide(10,4);"></li> <li id="11" class="fp de4"></li> You se that some of these have a button with a hide funcion. what i want is that when you press the hide button The following elements the have a highernumber in the .de# class should be hidden untill it reaches a LI with the same .de#-class. so if you press the hide(), i want LIs with ids 3,4,5,6,7 to be hiden. if i press the next on i want 4,5,6,7, and the thirs i want id 5 to be hidden. so this is the Javascript i made for it: function hide(id,de){ var de2 = de-1; $('#'+id).nextUntil('li.de'+de2).hide(); } The problem is that this function is not working exactly as i want. it would work correctly in the first hide()-function and the thirs but not in hide()function number two. here it will hide IDs: 4-8. so i want to do something. so i want the nextuntill() to hide elements untill it reaches a LI-element with the same .de# or a lower .de#. i hope i didn't complicate it to much in my description of the problem. if you have better idea than using nextUntill i'm all ears.

    Read the article

  • Monad in plain English? (For the OOP programmer with no FP background)

    - by fig-gnuton
    In terms that an OOP programmer would understand (without any functional programming background), what is a monad? What problem does it solve and what are the most common places it's used? EDIT: To clarify the kind of understanding I was looking for, let's say you were converting an FP application that had monads into an OOP application. What would you do to port the responsibilities of the monads into the OOP app?

    Read the article

  • Library order is important

    - by Darryl Gove
    I've written quite extensively about link ordering issues, but I've not discussed the interaction between archive libraries and shared libraries. So let's take a simple program that calls a maths library function: #include <math.h int main() { for (int i=0; i<10000000; i++) { sin(i); } } We compile and run it to get the following performance: bash-3.2$ cc -g -O fp.c -lm bash-3.2$ timex ./a.out real 6.06 user 6.04 sys 0.01 Now most people will have heard of the optimised maths library which is added by the flag -xlibmopt. This contains optimised versions of key mathematical functions, in this instance, using the library doubles performance: bash-3.2$ cc -g -O -xlibmopt fp.c -lm bash-3.2$ timex ./a.out real 2.70 user 2.69 sys 0.00 The optimised maths library is provided as an archive library (libmopt.a), and the driver adds it to the link line just before the maths library - this causes the linker to pick the definitions provided by the static library in preference to those provided by libm. We can see the processing by asking the compiler to print out the link line: bash-3.2$ cc -### -g -O -xlibmopt fp.c -lm /usr/ccs/bin/ld ... fp.o -lmopt -lm -o a.out... The flag to the linker is -lmopt, and this is placed before the -lm flag. So what happens when the -lm flag is in the wrong place on the command line: bash-3.2$ cc -g -O -xlibmopt -lm fp.c bash-3.2$ timex ./a.out real 6.02 user 6.01 sys 0.01 If the -lm flag is before the source file (or object file for that matter), we get the slower performance from the system maths library. Why's that? If we look at the link line we can see the following ordering: /usr/ccs/bin/ld ... -lmopt -lm fp.o -o a.out So the optimised maths library is still placed before the system maths library, but the object file is placed afterwards. This would be ok if the optimised maths library were a shared library, but it is not - instead it's an archive library, and archive library processing is different - as described in the linker and library guide: "The link-editor searches an archive only to resolve undefined or tentative external references that have previously been encountered." An archive library can only be used resolve symbols that are outstanding at that point in the link processing. When fp.o is placed before the libmopt.a archive library, then the linker has an unresolved symbol defined in fp.o, and it will search the archive library to resolve that symbol. If the archive library is placed before fp.o then there are no unresolved symbols at that point, and so the linker doesn't need to use the archive library. This is why libmopt needs to be placed after the object files on the link line. On the other hand if the linker has observed any shared libraries, then at any point these are checked for any unresolved symbols. The consequence of this is that once the linker "sees" libm it will resolve any symbols it can to that library, and it will not check the archive library to resolve them. This is why libmopt needs to be placed before libm on the link line. This leads to the following order for placing files on the link line: Object files Archive libraries Shared libraries If you use this order, then things will consistently get resolved to the archive libraries rather than to the shared libaries.

    Read the article

  • curl not returning content length header

    - by Michael P. Shipley
    Trying to get image file size using curl but content length header is not returned: $url ="http://www.collegefashion.net/wp-content/plugins/feed-comments-number/image.php?1263"; $fp = curl_init(); curl_setopt($fp, CURLOPT_NOBODY, true); curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1); curl_setopt($fp, CURLOPT_FAILONERROR,1); curl_setopt($fp, CURLOPT_REFERER,''); curl_setopt($fp, CURLOPT_URL, $url); curl_setopt($fp, CURLOPT_HEADER,1); curl_setopt($fp, CURLOPT_USERAGENT,'Mozilla/5.0'); $body = curl_exec($fp); var_dump($body): HTTP/1.1 200 OK Date: Sun, 02 May 2010 02:50:20 GMT Server: Apache/2.0.63 (CentOS) X-Powered-By: W3 Total Cache/0.8.5.2 X-Pingback: http://www.collegefashion.net/xmlrpc.php Cache-Control: no-cache, must-revalidate Expires: Sat, 26 Jul 1997 05:00:00 GMT Content-Type: image/png It works via ssh though: curl -i http://www.collegefashion.net/wp-content/plugins/feed-comments-number/image.php?1263 HTTP/1.1 200 OK Date: Sun, 02 May 2010 03:38:43 GMT Server: Apache/2.0.63 (CentOS) X-Powered-By: W3 Total Cache/0.8.5.2 X-Pingback: http://www.collegefashion.net/xmlrpc.php Cache-Control: no-cache, must-revalidate Expires: Sat, 26 Jul 1997 05:00:00 GMT Content-Length: 347 Content-Type: image/png

    Read the article

  • Unknown symbols when I read file

    - by Sergey Gavruk
    I read file, but in the end of file i get unknown symbols: int main() { char *buffer, ch; int i = 0, size; FILE *fp = fopen("file.txt", "r"); if(!fp){ printf("File not found!\n"); exit(1); } fseek(fp, 0, SEEK_END); size = ftell(fp); printf("%d\n", size); fseek(fp, 0, SEEK_SET); buffer = malloc(size * sizeof(*buffer)); while(((ch = fgetc(fp)) != NULL) && (i <= size)){ buffer[i++] = ch; } printf(buffer); fclose(fp); free(buffer); getch(); return 0; }

    Read the article

  • PHP's fopen is terminally failing

    - by Skittles
    Okay, I have GOT to be missing something totally rudimentary here. I have an extremely simple use of PHP's fopen function, but for some reason, it will not open the file no matter what I do. The odd part about this is that I use fopen in another function in the same script and it's working perfectly. I'm using the fclose in both functions. So, I know it's not a matter of a rogue file handle. I have confirmed the file's path and the existence of the target file also. I'm running the script at the command-line as root, so I know it's not apache that's the cause. And since I am running the script as root, I am fairly confident that permissions are not the issue. So, what on earth am I missing here? function get_file_list() { $file = '/home/site/tmp/return_files_list.txt'; $fp = fopen($file, 'r') or die("Could not open file: /home/site/tmp/return_files_list.txt for reading.\n"); $files_list = array(); while($line = fgets($fp)) { $files_list[] = $line; } fclose($fp); return $files_list; } function num_records_in_file($filename) { $fp = fopen( $filename, 'r' ); # or die("Could not open file: $filename\n"); $counter = 0; if ($fp) { while (!feof( $fp )) { $line = fgets( $fp ); $arr = explode( '|', $line ); if (( ( $arr[0] != 'HDR' && $arr[0] != 'TRL' ) && $arr[0] != '' )) { ++$counter; continue; } } } fclose( $fp ); return $counter; } As requested, here's both functions. The second function is passed an absolute path to the file. That is what I used to confirm that the file is there and that the path is correct.

    Read the article

  • Problem with reading and writing to binary file in C++

    - by Reem
    I need to make a file that contains "name" which is a string -array of char- and "data" which is array of bytes -array of char in C++- but the first problem I faced is how to separate the "name" from the "data"? newline character could work in this case (assuming that I don't have "\n" in the name) but I could have special characters in the "data" part so there's no way to know when it ends so I'm putting an int value in the file before the data which has the size of the "data"! I tried to do this with code as follow: if((fp = fopen("file.bin","wb")) == NULL) { return false; } char buffer[] = "first data\n"; fwrite( buffer ,1,sizeof(buffer),fp ); int number[1]; number[0]=10; fwrite( number ,1,1, fp ); char data[] = "1234567890"; fwrite( data , 1, number[0], fp ); fclose(fp); but I didn't know if the "int" part was right, so I tried many other codes including this one: char buffer[] = "first data\n"; fwrite( buffer ,1,sizeof(buffer),fp ); int size=10; fwrite( &size ,sizeof size,1, fp ); char data[] = "1234567890"; fwrite( data , 1, number[0], fp ); I see 4 "NULL" characters in the file when I open it instead of seeing an integer. Is that normal? The other problem I'm facing is reading that again from the file! The code I tried to read didn't work at all :( I tried it with "fread" but I'm not sure if I should use "fseek" with it or it just read the other character after it. Forgive me but I'm a beginner :(

    Read the article

  • A couple questions using fwrite/fread with data structures

    - by Nazgulled
    Hi, I'm using fwrite() and fread() for the first time to write some data structures to disk and I have a couple of questions about best practices and proper ways of doing things. What I'm writing to disk (so I can later read it back) is all user profiles inserted in a Graph structure. Each graph vertex is of the following type: typedef struct sUserProfile { char name[NAME_SZ]; char address[ADDRESS_SZ]; int socialNumber; char password[PASSWORD_SZ]; HashTable *mailbox; short msgCount; } UserProfile; And this is how I'm currently writing all the profiles to disk: void ioWriteNetworkState(SocialNetwork *social) { Vertex *currPtr = social->usersNetwork->vertices; UserProfile *user; FILE *fp = fopen("save/profiles.dat", "w"); if(!fp) { perror("fopen"); exit(EXIT_FAILURE); } fwrite(&(social->usersCount), sizeof(int), 1, fp); while(currPtr) { user = (UserProfile*)currPtr->value; fwrite(&(user->socialNumber), sizeof(int), 1, fp); fwrite(user->name, sizeof(char)*strlen(user->name), 1, fp); fwrite(user->address, sizeof(char)*strlen(user->address), 1, fp); fwrite(user->password, sizeof(char)*strlen(user->password), 1, fp); fwrite(&(user->msgCount), sizeof(short), 1, fp); break; currPtr = currPtr->next; } fclose(fp); } Notes: The first fwrite() you see will write the total user count in the graph so I know how much data I need to read back. The break is there for testing purposes. There's thousands of users and I'm still experimenting with the code. My questions: After reading this I decided to use fwrite() on each element instead of writing the whole structure. I also avoid writing the pointer to to the mailbox as I don't need to save that pointer. So, is this the way to go? Multiple fwrite()'s instead of a global one for the whole structure? Isn't that slower? How do I read back this content? I know I have to use fread() but I don't know the size of the strings, cause I used strlen() to write them. I could write the output of strlen() before writing the string, but is there any better way without extra writes?

    Read the article

  • Read and write struct in C

    - by Sergey
    I have a struct: typedef struct student { char fname[30]; char sname[30]; char tname[30]; Faculty fac; int course; char group[10]; int room; int bad; } Student; I read it from the file: Database * dbOpen(char *fname) { FILE *fp = fopen(fname, "rb"); List *lst, *temp; Student *std; Database *db = malloc(sizeof(*db)); if (!fp) return NULL; FileNameS = fname; std = malloc(sizeof(*std)); if (!fread(std, sizeof(*std), 1, fp)) { db->head = db->tail = NULL; return db; } lst = malloc(sizeof(*lst)); lst->s = std; lst->prev = NULL; db->head = lst; while (!feof(fp)) { fread(std, sizeof(*std), 1, fp); temp = malloc(sizeof(*temp)); temp->s = std; temp->prev = lst; lst->next = temp; lst = temp; } lst->next = NULL; db->tail = lst; fclose(fp); return db; } And I have a problem... At the last record i have a such file pointer: `fp 0x10311448 {_ptr=0x00344b90 "???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? _ _iobuf * ` And i read last record 2 times... Save file code: void * dbClose(Database *db) { FILE *fp = fopen(FileNameS, "w+b"); List *lst, *temp; lst = db->head; while(lst != NULL) { fwrite(lst->s, sizeof(*(lst->s)), 1, fp); temp = lst; lst = lst->next; free(temp); } free(db); fclose(fp); }

    Read the article

  • Function Point Analysis -- a seriously over-estimating technique?

    - by kizzx2
    I know questions about FPA has been asked numerous times before, but this time I'm taking a more analytical angle at it, backed up with data. 1. First, some data This question is based on a tutorial. He had a "Sample Count" section where he demonstrated it step by step. You can see some screenshots of his sample application here. In the end, he calculated the unadjusted FP to be 99. There is another article on InformIT with industry data on typical hour/FP. It ranges from 2 hours/FP to 27.4 hours/FP. Let's try to stick with 2 for the moment (since SO readers are probably the more efficient crowd :p). 2. Reality check!? Now just check out the screenshots again. Do a little math here 99 * 2 = 198 hours 198 hours / 40 hours per week = 5 weeks Seriously? That sample application is going to take 5 weeks to implement? Is it just my feeling that it wouldn't take any decent programmer longer than one week to have it completed? Now let's try estimating the cost of the project. We'll use New York's minimum wage at the moment (Wikipedia), which is $7.25 198 * 7.25 = $1435.5 From what I could see from the screenshots, this application is a small excel-improvement app. I could have bought MS Office Pro for 200 bucks which gives me greater interoperability (.xls files) and flexibility (spreadsheets). (For the record, that same Web site has another article discussing productivity. It seems like they typically use 4.2 hours/FP, which gives us even more shocking stats: 99 * 4.2 = 415 hours = 10 weeks = almost 3 whopping months! 415 hours * $7.25 = $3000 zomg (That's even assuming that all our poor coders get the minimum wage!) 3. Am I missing something here? Right now, I could come up with several possible explanation: FPA is really only suited for bigger projects (1000+ FPs) so it becomes extremely inaccurate at smaller scale. The hours/FP metric fluctuates abruptly from team to team, project to project. For a small project like this, we could have used something like 0.5 hour/FP or something. (Now this kind of makes the whole estimation thing pointless, unless my firm does the same type of projects for several years with the same team, not really common.) From my experience with several software metrics, Function Point is really not a lightweight metric. If the hour/FP thing fluctuates so much, then what's the point, maybe I could have gone with User Story Points which is a lot faster to get and arguably almost as uncertain. What would be the FP experts' answers to this?

    Read the article

  • Function Point Analysis -- a seriously overestimating technique?

    - by kizzx2
    I know questions about FPA has been asked numerous times before, but this time I'm taking a more analytical angle at it, backed up with data. 1. First, some data This question is based on a tutorial. He had a "Sample Count" section where he demonstrated it step by step. You can see some screenshots of his sample application here. In the end, he calculated the unadjusted FP to be 99. There is another article on InformIT with industry data on typical hour/FP. It ranges from 2 hours/FP to 27.4 hours/FP. Let's try to stick with 2 for the moment (since SO readers are probably the more efficient crowd :p). 2. Reality check!? Now just check out the screenshots again. Do a little math here 99 * 2 = 198 hours 198 hours / 40 hours per week = 5 weeks Seriously? That sample application is going to take 5 weeks to implement? Is it just my feeling that it wouldn't take any decent programmer longer than one week (I"m not even saying weekend) to have it completed? Now let's try estimating the cost of the project. We'll use New York's minimum wage at the moment (Wikipedia), which is $7.25 198 * 7.25 = $1435.5 From what I could see from the screenshots, this application is a small excel-improvement app. I could have bought MS Office Pro for 200 bucks which gives me greater interoperability (.xls files) and flexibility (spreadsheets). (For the record, that same Web site has another article discussing productivity. It seems like they typically use 4.2 hours/FP, which gives us even more shocking stats: 99 * 4.2 = 415 hours = 10 weeks = almost 3 whopping months! 415 hours * $7.25 = $3000 zomg (That's even assuming that all our poor coders get the minimum wage!) 3. Am I missing something here? Right now, I could come up with several possible explanation: FPA is really only suited for bigger projects (1000+ FPs) so it becomes extremely inaccurate at smaller scale. The hours/FP metric fluctuates abruptly from team to team, project to project. For a small project like this, we could have used something like 0.5 hour/FP or something. (Now this kind of makes the whole estimation thing pointless, unless my firm does the same type of projects for several years with the same team, not really common.) From my experience with several software metrics, Function Point is really not a lightweight metric. If the hour/FP thing fluctuates so much, then what's the point, maybe I could have gone with User Story Points which is a lot faster to get and arguably almost as uncertain. What would be the FP experts' answers to this?

    Read the article

  • c++ function overloading, making fwrite/fread act like PHP versions

    - by Newbie
    I'm used to the PHP fwrite/fread parameter orders, and i want to make them the same in C++ too. I want it to work with char and string types, and also any data type i put in it (only if length is defined). I am total noob on c++, this is what i made so far: size_t fwrite(FILE *fp, const std::string buf, const size_t len = SIZE_MAX){ if(len == SIZE_MAX){ return fwrite(buf.c_str(), 1, buf.length(), fp); }else{ return fwrite(buf.c_str(), 1, len, fp); } } size_t fwrite(FILE *fp, const void *buf, const size_t len = SIZE_MAX){ if(len == SIZE_MAX){ return fwrite((const char *)buf, 1, strlen((const char *)buf), fp); }else{ return fwrite(buf, 1, len, fp); } } Should this work just fine? And how should this be done if i wanted to do it the absolutely best possible way?

    Read the article

  • How can I compare the performance of log() and fp division in C++?

    - by Ventzi Zhechev
    Hi, I’m using a log-based class in C++ to store very small floating-point values (as the values otherwise go beyond the scope of double). As I’m performing a large number of multiplications, this has the added benefit of converting the multiplications to sums. However, at a certain point in my algorithm, I need to divide a standard double value by an integer value and than do a *= to a log-based value. I have overloaded the *= operator for my log-based class and the right-hand side value is first converted to a log-based value by running log() and than added to the left-hand side value. Thus the operations actually performed are floating-point division, log() and floating-point summation. My question whether it would be faster to first convert the denominator to a log-based value, which would replace the floating-point division with floating-point subtraction, yielding the following chain of operations: twice log(), floating-point subtraction, floating-point summation. In the end, this boils down to whether floating-point division is faster or slower than log(). I suspect that a common answer would be that this is compiler and architecture dependent, so I’ll say that I use gcc 4.2 from Apple on darwin 10.3.0. Still, I hope to get an answer with a general remark on the speed of these two operators and/or an idea on how to measure the difference myself, as there might be more going on here, e.g. executing the constructors that do the type conversion etc. Cheers!

    Read the article

  • Composing programs from small simple pieces: OOP vs Functional Programming

    - by Jay Godse
    I started programming when imperative programming languages such as C were virtually the only game in town for paid gigs. I'm not a computer scientist by training so I was only exposed to Assembler and Pascal in school, and not Lisp or Prolog. Over the 1990s, Object-Oriented Programming (OOP) became more popular because one of the marketing memes for OOP was that complex programs could be composed of loosely coupled but well-defined, well-tested, cohesive, and reusable classes and objects. And in many cases that is quite true. Once I learned object-oriented programming my C programs became better because I structured them more like classes and objects. In the last few years (2008-2014) I have programmed in Ruby, an OOP language. However, Ruby has many functional programming (FP) features such as lambdas and procs, which enable a different style of programming using recursion, currying, lazy evaluation and the like. (Through ignorance I am at a loss to explain why these techniques are so great). Very recently, I have written code to use methods from the Ruby Enumerable library, such as map(), reduce(), and select(). Apparently this is a functional style of programming. I have found that using these methods significantly reduce code volume, and make my code easier to debug. Upon reading more about FP, one of the marketing claims made by advocates is that FP enables developers to compose programs out of small well-defined, well-tested, and reusable functions, which leads to less buggy code, and low code volume. QUESTIONS: Is the composition of complex program by using FP techniques contradictory to or complementary to composition of a complex program by using OOP techniques? In which situations is OOP more effective, and when is FP more effective? Is it possible to use both techniques in the same complex program? Do the techniques overlap or contradict each other?

    Read the article

  • Problem in transfering file from server to client using C sockets

    - by coolrockers2007
    I want to ask, why I cannot transfer file from server to client? When I start to send the file from server, the client side program will have problem. So, I spend some times to check the code, But I still cannot find out the problem Can anyone point out the problem for me? CLIENTFILE.C #include stdio.h #include stdlib.h #include time.h #include netinet/in.h #include fcntl.h #include sys/types.h #include string.h #include stdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int sockfd; int number,message; char outbuff[MLEN],inbuff[MLEN]; //char PWD_buffer[_MAX_PATH]; struct sockaddr_in servaddr; FILE *fp; int numbytes; char buf[2048]; if (argc != 2) fprintf(stderr, "error"); if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) fprintf(stderr, "socket error"); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr, "connect error"); if ( (fp = fopen("/home/na/nall9047/write.txt", "w")) == NULL){ perror("fopen"); exit(1); } printf("Still NO PROBLEM!\n"); //Receive file from server while(1){ numbytes = read(sockfd, buf, sizeof(buf)); printf("read %d bytes, ", numbytes); if(numbytes == 0){ printf("\n"); break; } numbytes = fwrite(buf, sizeof(char), numbytes, fp); printf("fwrite %d bytes\n", numbytes); } fclose(fp); close(sockfd); return 0; } SERVERFILE.C #include stdio.h #include fcntl.h #include stdlib.h #include time.h #include string.h #include netinet/in.h #include errno.h #include sys/types.h #include sys/socket.h #includ estdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int listenfd, connfd; int number, message, numbytes; int h, i, j, alen; int nread; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; FILE *in_file, *out_file, *fp; char buf[4096]; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) fprintf(stderr,"listen error") ; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr,"bind error") ; alen = sizeof(struct sockaddr); connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &alen); if (connfd < 0) fprintf(stderr,"error connecting") ; printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr)); fp = fopen ("/home/na/nall9047/read.txt", "r"); // open file stored in server if (fp == NULL) { printf("\nfile NOT exist"); } //Sending file while(!feof(fp)){ numbytes = fread(buf, sizeof(char), sizeof(buf), fp); printf("fread %d bytes, ", numbytes); numbytes = write(connfd, buf, numbytes); printf("Sending %d bytes\n",numbytes); } fclose (fp); close(listenfd); close(connfd); return 0; }

    Read the article

  • fsockopen soap request

    - by gosom
    I am trying to send a SOAP message to a service using php. I want to do it with fsockopen, here's is the code : <?php $fp = @fsockopen("ssl://xmlpropp.worldspan.com", 443, $errno, $errstr); if (!is_resource($fp)) { die('fsockopen call failed with error number ' . $errno . '.' . $errstr); } $soap_out = "POST /xmlts HTTP/1.1\r\n"; $soap_out .= "Host: 212.127.18.11:8800\r\n"; //$soap_out .= "User-Agent: MySOAPisOKGuys \r\n"; $soap_out .= "Content-Type: text/xml; charset='utf-8'\r\n"; $soap_out .= "Content-Length: 999\r\n\r\n"; $soap_put .= "Connection: close\r\n"; $soap_out .= "SOAPAction:\r\n"; $soap_out .= ' Worldspan This is a test '; if(!fputs($fp, $soap_out, strlen($soap_out))) echo "could not write"; echo "<xmp>".$soap_out."</xmp>"; echo "--------------------<br>"; while (!feof($fp)) { $soap_in .= fgets($fp, 100); } echo "<xmp>$soap_in</xmp>"; fclose($fp); echo "ok"; the above code just hangs . if i remove the while it types ok, so i suppose the problem is at $soap_in .= fgets($fp, 100) Any ideas of what is happening

    Read the article

  • Using PHP to store results of a post request

    - by Paul M
    Im currently working with an API which requires we send our collection details in xml to their server using a post request. Nothing major there but its not working, so I want to output the sent xml to a txt file so I can look at actually whats being sent!! Instead of posting to the API im posting to a document called target, but the xml its outputting its recording seems to be really wrong. Here is my target script, note that the posting script posts 3 items, so the file being written should have details of each post request one after the other. <?php error_reporting(E_ALL); ini_set('display_errors', 1); // get the request data... $payload = ''; $fp = fopen('php://input','r'); $output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); fwrite($output_file, $payload); } fclose($fp); fclose($output_file); ?> I also tried the following, but this just recorded the last post request so only 1 collection item was recorded in the txt file, instead of all 3 output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); } fwrite($output_file, $payload); fclose($fp); fclose($output_file); I know im missing something really obvious, but ive been looking at this all morning!

    Read the article

  • Loading machinecode from file into memory and executing in C -- mprotect failing

    - by chartreusekitsune
    Hi I'm trying to load raw machine code into memory and run it from within a C program, right now when the program executes it breaks when trying to run mprotect on the memory to make it executable. I'm also not entirely sure that if the memory does get set right it will execute. What I currently have is the following: #include <memory.h> #include <sys/mman.h> #include <stdio.h> int main ( int argc, char **argv ) { FILE *fp; int sz = 0; char *membuf; int output = 0; fp = fopen(argv[1],"rb"); if(fp == NULL) { printf("Failed to open file, aborting!\n"); exit(1); } fseek(fp, 0L, SEEK_END); sz = ftell(fp); fseek(fp, 0L, SEEK_SET); membuf = (char *)malloc(sz*sizeof(char)); if(membuf == NULL) { printf("Failed to allocate memory, aborting!\n"); exit(1); } memset(membuf, 0x90, sz*sizeof(char)); if( mprotect(membuf, sz*sizeof(char), PROT_EXEC | PROT_READ | PROT_WRITE) == -1) { printf("mprotect failed!!! aborting!\n"); exit(1); } if((sz*sizeof(char)) != fread(membuf, sz*sizeof(char), 1, fp)) { printf("Read failed, aborting!\n"); exit(1); } __asm__ ( "call %%eax;" : "=a" (output) : "a" (membuf) ); printf("Output = %x\n", output); return 0; }

    Read the article

  • PayPal IPN - having trouble accessing session data?

    - by Martin Bean
    Hello, all. I'm having issues with PayPal IPN integration where it seems I cannot get my solution to read session variables. Basically, in my shop module script, I store the customer's details as provided by PayPal to an orders table. However, I also wish to save products ordered in a transaction to a separate table linked by the order ID. However, it's the second part of the script that's not working, where I loop through the products in the session and then save them to the orders_products table. Is there a reason why the session data not being read? The code within shop.php is as follows: if ($paypal->validate_ipn()) { $name = $paypal->ipn_data['address_name']; $street_1 = $paypal->ipn_data['address_street']; $street_2 = ""; $city = $paypal->ipn_data['address_city']; $state = $paypal->ipn_data['address_state']; $zip = $paypal->ipn_data['address_zip']; $country = $paypal->ipn_data['address_country']; $txn_id = $paypal->ipn_data['txn_id']; $sql = "INSERT INTO orders (name, street_1, street_2, city, state, zip, country, txn_id) VALUES (:name, :street_1, :street_2, :city, :state, :zip, :country, :txn_id)"; $smt = $this->pdo->prepare($sql); $smt->bindParam(':name', $name, PDO::PARAM_STR); $smt->bindParam(':street_1', $street_1, PDO::PARAM_STR); $smt->bindParam(':street_2', $street_2, PDO::PARAM_STR); $smt->bindParam(':city', $city, PDO::PARAM_STR); $smt->bindParam(':state', $state, PDO::PARAM_STR); $smt->bindParam(':zip', $zip, PDO::PARAM_STR); $smt->bindParam(':country', $country, PDO::PARAM_STR); $smt->bindParam(':txn_id', $txn_id, PDO::PARAM_INT); $smt->execute(); // save products to orders relationship $order_id = $this->pdo->lastInsertId(); // $cart = $this->session->get('cart'); $cart = $this->session->get('cart'); foreach ($cart as $product_id => $item) { $quantity = $item['quantity']; $sql = "INSERT INTO orders_products (order_id, product_id, quantity) VALUES ('$order_id', '$product_id', '$quantity')"; $res = $this->pdo->query($sql); } $this->session->del('cart'); mail('[email protected]', 'IPN result', 'IPN was successful on wrestling-wear.com'); } else { mail('[email protected]', 'IPN result', 'IPN failed on wrestling-wear.com'); } And I'm using the PayPal IPN class for PHP as found here: http://www.micahcarrick.com/04-19-2005/php-paypal-ipn-integration-class.html, but the contents of the validate_ipn() method is as follows: public function validate_ipn() { $url_parsed = parse_url($this->paypal_url); $post_string = ''; foreach ($_POST as $field => $value) { $this->ipn_data[$field] = $value; $post_string.= $field.'='.urlencode(stripslashes($value)).'&'; } $post_string.= "cmd=_notify-validate"; // append IPN command // open the connection to PayPal $fp = fsockopen($url_parsed[host], "80", $err_num, $err_str, 30); if (!$fp) { // could not open the connection. If logging is on, the error message will be in the log $this->last_error = "fsockopen error no. $errnum: $errstr"; $this->log_ipn_results(false); return false; } else { // post the data back to PayPal fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); fputs($fp, "Host: $url_parsed[host]\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $post_string . "\r\n\r\n"); // loop through the response from the server and append to variable while (!feof($fp)) { $this->ipn_response.= fgets($fp, 1024); } fclose($fp); // close connection } if (eregi("VERIFIED", $this->ipn_response)) { // valid IPN transaction $this->log_ipn_results(true); return true; } else { // invalid IPN transaction; check the log for details $this->last_error = 'IPN Validation Failed.'; $this->log_ipn_results(false); return false; } }

    Read the article

  • php_network_getaddresses: getaddrinfo failed: Name or service not known

    - by Rob
    Here is a snippet of my code $fp = fsockopen($s['url'], 80, $errno, $errstr, 5); if($fp){ fwrite($fp, $out); fclose($fp); When I run it, it outputs: unable to connect to www.mydomain.net/1/file.php:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known I can't figure out why. Any help would be greatly appreciated. EDIT: I forgot to mention that I'm using this to submit GET data to the $s['url']

    Read the article

  • Invoking a function of library libfprint in Python

    - by Ivanelson
    I need help to call a function(Struct C) that detects the devices, so I'm calling the function this way: from ctypes import * fp = CDLL('./libfprint.so.0') fp.fp_discover_devs.argtypes = None fp.fp_discover_devs.restype = c_char_p ret = fp.fp_discover_devs() print ret # is "0" That is not detected any device, because the return is "0". See the documentation of the function: I'm using Ubuntu and I downloaded the "fprint_demo" and works perfectly. Did you install any package missing? Thanks.

    Read the article

  • How to tell endianness from this output?

    - by Nick Rosencrantz
    I'm running this example program and I'm suppossed to be able to tell from the output what machine type it is. I'm certain it's from inspecting one or two values but how should I perform this inspection? /* pointers.c - Test pointers * Written 2012 by F Lundevall * Copyright abandoned. This file is in the public domain. * * To make this program work on as many systems as possible, * addresses are converted to unsigned long when printed. * The 'l' in formatting-codes %ld and %lx means a long operand. */ #include <stdio.h> #include <stdlib.h> int * ip; /* Declare a pointer to int, a.k.a. int pointer. */ char * cp; /* Pointer to char, a.k.a. char pointer. */ /* Declare fp as a pointer to function, where that function * has one parameter of type int and returns an int. * Use cdecl to get the syntax right, http://cdecl.org/ */ int ( *fp )( int ); int val1 = 111111; int val2 = 222222; int ia[ 17 ]; /* Declare an array of 17 ints, numbered 0 through 16. */ char ca[ 17 ]; /* Declare an array of 17 chars. */ int fun( int parm ) { printf( "Function fun called with parameter %d\n", parm ); return( parm + 1 ); } /* Main function. */ int main() { printf( "Message PT.01 from pointers.c: Hello, pointy World!\n" ); /* Do some assignments. */ ip = &val1; cp = &val2; /* The compiler should warn you about this. */ fp = fun; ia[ 0 ] = 11; /* First element. */ ia[ 1 ] = 17; ia[ 2 ] = 3; ia[ 16 ] = 58; /* Last element. */ ca[ 0 ] = 11; /* First element. */ ca[ 1 ] = 17; ca[ 2 ] = 3; ca[ 16 ] = 58; /* Last element. */ printf( "PT.02: val1: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val1, val1, val1 ); printf( "PT.03: val2: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val2, val2, val2 ); printf( "PT.04: ip: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &ip, (long) ip, (long) ip ); printf( "PT.05: Dereference pointer ip and we find: %d \n", *ip ); printf( "PT.06: cp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &cp, (long) cp, (long) cp ); printf( "PT.07: Dereference pointer cp and we find: %d \n", *cp ); *ip = 1234; printf( "\nPT.08: Executed *ip = 1234; \n" ); printf( "PT.09: val1: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val1, val1, val1 ); printf( "PT.10: ip: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &ip, (long) ip, (long) ip ); printf( "PT.11: Dereference pointer ip and we find: %d \n", *ip ); printf( "PT.12: val1: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val1, val1, val1 ); *cp = 1234; /* The compiler should warn you about this. */ printf( "\nPT.13: Executed *cp = 1234; \n" ); printf( "PT.14: val2: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val2, val2, val2 ); printf( "PT.15: cp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &cp, (long) cp, (long) cp ); printf( "PT.16: Dereference pointer cp and we find: %d \n", *cp ); printf( "PT.17: val2: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val2, val2, val2 ); ip = ia; printf( "\nPT.18: Executed ip = ia; \n" ); printf( "PT.19: ia[0]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ia[0], ia[0], ia[0] ); printf( "PT.20: ia[1]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ia[1], ia[1], ia[1] ); printf( "PT.21: ip: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &ip, (long) ip, (long) ip ); printf( "PT.22: Dereference pointer ip and we find: %d \n", *ip ); ip = ip + 1; /* add 1 to pointer */ printf( "\nPT.23: Executed ip = ip + 1; \n" ); printf( "PT.24: ip: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &ip, (long) ip, (long) ip ); printf( "PT.25: Dereference pointer ip and we find: %d \n", *ip ); cp = ca; printf( "\nPT.26: Executed cp = ca; \n" ); printf( "PT.27: ca[0]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ca[0], ca[0], ca[0] ); printf( "PT.28: ca[1]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ca[1], ca[1], ca[1] ); printf( "PT.29: cp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &cp, (long) cp, (long) cp ); printf( "PT.30: Dereference pointer cp and we find: %d \n", *cp ); cp = cp + 1; /* add 1 to pointer */ printf( "\nPT.31: Executed cp = cp + 1; \n" ); printf( "PT.32: cp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &cp, (long) cp, (long) cp ); printf( "PT.33: Dereference pointer cp and we find: %d \n", *cp ); ip = ca; /* The compiler should warn you about this. */ printf( "\nPT.34: Executed ip = ca; \n" ); printf( "PT.35: ca[0]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ca[0], ca[0], ca[0] ); printf( "PT.36: ca[1]: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &ca[1], ca[1], ca[1] ); printf( "PT.37: ip: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &ip, (long) ip, (long) ip ); printf( "PT.38: Dereference pointer ip and we find: %d \n", *ip ); cp = ia; /* The compiler should warn you about this. */ printf( "\nPT.39: Executed cp = ia; \n" ); printf( "PT.40: cp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &cp, (long) cp, (long) cp ); printf( "PT.41: Dereference pointer cp and we find: %d \n", *cp ); printf( "\nPT.42: fp: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", (long) &fp, (long) fp, (long) fp ); printf( "PT.43: Dereference fp and see what happens.\n" ); val1 = (*fp)(42); printf( "PT.44: Executed val1 = (*fp)(42); \n" ); printf( "PT.45: val1: stored at %lx (hex); value is %d (dec), %x (hex)\n", (long) &val1, val1, val1 ); return( 0 ); } Output Message PT.01 from pointers.c: Hello, pointy World! PT.02: val1: stored at 21e50 (hex); value is 111111 (dec), 1b207 (hex) PT.03: val2: stored at 21e54 (hex); value is 222222 (dec), 3640e (hex) PT.04: ip: stored at 21eb8 (hex); value is 138832 (dec), 21e50 (hex) PT.05: Dereference pointer ip and we find: 111111 PT.06: cp: stored at 21e6c (hex); value is 138836 (dec), 21e54 (hex) PT.07: Dereference pointer cp and we find: 0 PT.08: Executed *ip = 1234; PT.09: val1: stored at 21e50 (hex); value is 1234 (dec), 4d2 (hex) PT.10: ip: stored at 21eb8 (hex); value is 138832 (dec), 21e50 (hex) PT.11: Dereference pointer ip and we find: 1234 PT.12: val1: stored at 21e50 (hex); value is 1234 (dec), 4d2 (hex) PT.13: Executed *cp = 1234; PT.14: val2: stored at 21e54 (hex); value is -771529714 (dec), d203640e (hex) PT.15: cp: stored at 21e6c (hex); value is 138836 (dec), 21e54 (hex) PT.16: Dereference pointer cp and we find: -46 PT.17: val2: stored at 21e54 (hex); value is -771529714 (dec), d203640e (hex) PT.18: Executed ip = ia; PT.19: ia[0]: stored at 21e74 (hex); value is 11 (dec), b (hex) PT.20: ia[1]: stored at 21e78 (hex); value is 17 (dec), 11 (hex) PT.21: ip: stored at 21eb8 (hex); value is 138868 (dec), 21e74 (hex) PT.22: Dereference pointer ip and we find: 11 PT.23: Executed ip = ip + 1; PT.24: ip: stored at 21eb8 (hex); value is 138872 (dec), 21e78 (hex) PT.25: Dereference pointer ip and we find: 17 PT.26: Executed cp = ca; PT.27: ca[0]: stored at 21e58 (hex); value is 11 (dec), b (hex) PT.28: ca[1]: stored at 21e59 (hex); value is 17 (dec), 11 (hex) PT.29: cp: stored at 21e6c (hex); value is 138840 (dec), 21e58 (hex) PT.30: Dereference pointer cp and we find: 11 PT.31: Executed cp = cp + 1; PT.32: cp: stored at 21e6c (hex); value is 138841 (dec), 21e59 (hex) PT.33: Dereference pointer cp and we find: 17 PT.34: Executed ip = ca; PT.35: ca[0]: stored at 21e58 (hex); value is 11 (dec), b (hex) PT.36: ca[1]: stored at 21e59 (hex); value is 17 (dec), 11 (hex) PT.37: ip: stored at 21eb8 (hex); value is 138840 (dec), 21e58 (hex) PT.38: Dereference pointer ip and we find: 185664256 PT.39: Executed cp = ia; PT.40: cp: stored at 21e6c (hex); value is 138868 (dec), 21e74 (hex) PT.41: Dereference pointer cp and we find: 0 PT.42: fp: stored at 21e70 (hex); value is 69288 (dec), 10ea8 (hex) PT.43: Dereference fp and see what happens. Function fun called with parameter 42 PT.44: Executed val1 = (*fp)(42); PT.45: val1: stored at 21e50 (hex); value is 43 (dec), 2b (hex)

    Read the article

  • C Language: Why I cannot transfer file from server to client?

    - by user275753
    I want to ask, why I cannot transfer file from server to client? When I start to send the file from server, the client side program will have problem. So, I spend some times to check the code, But I still cannot find out the problem Can anyone point out the problem for me? thanks a lot! [client side code] include include include include include include include define SA struct sockaddr define S_PORT 5678 define MAXLEN 1000 define true 1 void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1); } int main(int argc, char *argv []) { WSADATA wsadata; SOCKET sockfd; int number,message; char outbuff[MAXLEN],inbuff[MAXLEN]; char PWD_buffer[_MAX_PATH]; struct sockaddr_in servaddr; FILE *fp; int numbytes; char buf[2048]; if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); if (argc != 2) errexit("client IPaddress"); if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET ) errexit("socket error: error number %d\n", WSAGetLastError()); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(S_PORT); if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE) errexit("inet_addr error: error number %d\n", WSAGetLastError()); if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) errexit("connect error: error number %d\n", WSAGetLastError()); if ( (fp = fopen("C:\\users\\pc\\desktop\\COPY.c", "wb")) == NULL){ perror("fopen"); exit(1); } printf("Still NO PROBLEM!\n"); //Receive file from server while(1){ numbytes = read(sockfd, buf, sizeof(buf)); printf("read %d bytes, ", numbytes); if(numbytes == 0){ printf("\n"); break; } numbytes = fwrite(buf, sizeof(char), numbytes, fp); printf("fwrite %d bytes\n", numbytes); } fclose(fp); close(sockfd); return 0; } server side code include include include include include include include include define SA struct sockaddr define S_PORT 5678 define MAXLEN 1000 void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1); } int main(int argc, char *argv []) { WSADATA wsadata; SOCKET listenfd, connfd; int number, message, numbytes; int h, i, j, alen; int nread; struct sockaddr_in servaddr, cliaddr; FILE *in_file, *out_file, *fp; char buf[4096]; if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == INVALID_SOCKET) errexit("cannot create socket: error number %d\n", WSAGetLastError()); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(S_PORT); if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) errexit("can't bind to port %d: error number %d\n", S_PORT, WSAGetLastError()); if (listen(listenfd, 5) == SOCKET_ERROR) errexit("can't listen on port %d: error number %d\n", S_PORT, WSAGetLastError()); alen = sizeof(SA); connfd = accept(listenfd, (SA *) &cliaddr, &alen); if (connfd == INVALID_SOCKET) errexit("accept failed: error number %d\n", WSAGetLastError()); printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr)); fp = fopen ("client.c", "rb"); // open file stored in server if (fp == NULL) { printf("\nfile NOT exist"); } //Sending file while(!feof(fp)){ numbytes = fread(buf, sizeof(char), sizeof(buf), fp); printf("fread %d bytes, ", numbytes); numbytes = write(connfd, buf, numbytes); printf("Sending %d bytes\n",numbytes); } fclose (fp); closesocket(listenfd); closesocket(connfd); return 0; }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >