Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 10/74 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • C program using inotify to monitor multiple directories along with sub-directories?

    - by lakshmipathi
    I have program which monitors a directory (/test) and notify me. I want to improve this to monitor another directory (say /opt). And also how to monitor it's subdirectories , current i'll get notified if any changes made to files under /test . but i'm not getting any inotifcation if changes made sub-directory of /test, that is touch /test/sub-dir/files.txt .. Here my current code - hope this will help /* Simple example for inotify in Linux. inotify has 3 main functions. inotify_init1 to initialize inotify_add_watch to add monitor then inotify_??_watch to rm monitor.you the what to replace with ??. yes third one is inotify_rm_watch() */ #include <sys/inotify.h> int main(){ int fd,wd,wd1,i=0,len=0; char pathname[100],buf[1024]; struct inotify_event *event; fd=inotify_init1(IN_NONBLOCK); /* watch /test directory for any activity and report it back to me */ wd=inotify_add_watch(fd,"/test",IN_ALL_EVENTS); while(1){ //read 1024 bytes of events from fd into buf i=0; len=read(fd,buf,1024); while(i<len){ event=(struct inotify_event *) &buf[i]; /* check for changes */ if(event->mask & IN_OPEN) printf("%s :was opened\n",event->name); if(event->mask & IN_MODIFY) printf("%s : modified\n",event->name); if(event->mask & IN_ATTRIB) printf("%s :meta data changed\n",event->name); if(event->mask & IN_ACCESS) printf("%s :was read\n",event->name); if(event->mask & IN_CLOSE_WRITE) printf("%s :file opened for writing was closed\n",event->name); if(event->mask & IN_CLOSE_NOWRITE) printf("%s :file opened not for writing was closed\n",event->name); if(event->mask & IN_DELETE_SELF) printf("%s :deleted\n",event->name); if(event->mask & IN_DELETE) printf("%s :deleted\n",event->name); /* update index to start of next event */ i+=sizeof(struct inotify_event)+event->len; } } }

    Read the article

  • Why is my producer-consumer blocking?

    - by User007
    My code is here: http://pastebin.com/Fi3h0E0P Here is the output 0 Should we take order today (y or n): y Enter order number: 100 More customers (y or n): n Stop serving customers right now. Passing orders to cooker: There are total of 1 order(s) 1 Roger, waiter. I am processing order #100 The goal is waiter must take orders and then give them to the cook. The waiter has to wait cook finishes all pizza, deliver the pizza, and then take new orders. I asked how P-V work in my previous post here. I don't think it has anything to do with \n consuming? I tried all kinds of combination of wait(), but none work. Where did I make a mistake? The main part is here: //Producer process if(pid > 0) { while(1) { printf("0"); P(emptyShelf); // waiter as P finds no items on shelf; P(mutex); // has permission to use the shelf waiter_as_producer(); V(mutex); // cooker now can use the shelf V(orderOnShelf); // cooker now can pickup orders wait(); printf("2"); P(pizzaOnShelf); P(mutex); waiter_as_consumer(); V(mutex); V(emptyShelf); printf("3 "); } } if(pid == 0) { while(1) { printf("1"); P(orderOnShelf); // make sure there is an order on shelf P(mutex); //permission to work cooker_as_consumer(); // take order and put pizza on shelf printf("return from cooker"); V(mutex); //release permission printf("just released perm"); V(pizzaOnShelf); // pizza is now on shelf printf("after"); wait(); printf("4"); } } So I imagine this is the execution path: enter waiter_as_producer, then go to child process (cooker), then transfer the control back to parent, finish waiter_as_consumer, switch back to child. The two waits switch back to parent (like I said I tried all possible wait() combination...).

    Read the article

  • Question about InputMismatchException while using Scanner

    - by aser
    The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: $%.2f %n",BeginningBalance); outFile.printf("Ending Balance: $%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: $%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: $%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: $%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

    Read the article

  • Help me with this java program

    - by aser
    The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: $%.2f %n",BeginningBalance); outFile.printf("Ending Balance: $%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: $%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: $%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: $%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

    Read the article

  • How to create a simple Proxy to access web servers in C

    - by jesusiniesta
    Hi. I’m trying to create an small Web Proxy in C. First, I’m trying to get a webpage, sending a GET frame to the server. I don’t know what I have missed, but I am not receiving any response. I would really appreciate if you can help me to find what is missing in this code. int main (int argc, char** argv) { int cache_size, //size of the cache in KiB port, port_google = 80, dir, mySocket, socket_google; char google[] = "www.google.es", ip[16]; struct sockaddr_in socketAddr; char buffer[10000000]; if (GetParameters(argc,argv,&cache_size,&port) != 0) return -1; GetIP (google, ip); printf("ip2 = %s\n",ip); dir = inet_addr (ip); printf("ip3 = %i\n",dir); /* Creation of a socket with Google */ socket_google = conectClient (port_google, dir, &socketAddr); if (socket_google < 0) return -1; else printf("Socket created\n"); sprintf(buffer,"GET /index.html HTTP/1.1\r\n\r\n"); if (write(socket_google, (void*)buffer, LONGITUD_MSJ+1) < 0 ) return 1; else printf("GET frame sent\n"); strcpy(buffer,"\n"); read(socket_google, buffer, sizeof(buffer)); // strcpy(message,buffer); printf("%s\n", buffer); return 0; } And this is the code I use to create the socket. I think this part is OK, but I copy it just in case. int conectClient (int puerto, int direccion, struct sockaddr_in *socketAddr) { int mySocket; char error[1000]; if ( (mySocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("Error when creating the socket\n"); return -2; } socketAddr->sin_family = AF_INET; socketAddr->sin_addr.s_addr = direccion; socketAddr->sin_port = htons(puerto); if (connect (mySocket, (struct sockaddr *)socketAddr,sizeof (*socketAddr)) == -1) { snprintf(error, sizeof(error), "Error in %s:%d\n", __FILE__, __LINE__); perror(error); printf("%s\n",error); printf ("-- Error when stablishing a connection\n"); return -1; } return mySocket; } Thanks!

    Read the article

  • Router Alert options on IGMPv2 packets

    - by Scakko
    I'm trying to forge an IGMPv2 Membership Request packet and send it on a RAW socket. The RFC 3376 states: IGMP messages are encapsulated in IPv4 datagrams, with an IP protocol number of 2. Every IGMP message described in this document is sent with an IP Time-to-Live of 1, IP Precedence of Internetwork Control (e.g., Type of Service 0xc0), and carries an IP Router Alert option [RFC-2113] in its IP header So the IP_ROUTER_ALERT flag must be set. I'm trying to forge the strict necessary of the packet (e.g. only the IGMP header & payload), so i'm using the setsockopt to edit the IP options. some useful variables: #define C_IP_MULTICAST_TTL 1 #define C_IP_ROUTER_ALERT 1 int sockfd = 0; int ecsockopt = 0; int bytes_num = 0; int ip_multicast_ttl = C_IP_MULTICAST_TTL; int ip_router_alert = C_IP_ROUTER_ALERT; Here's how I open the RAW socket: sock_domain = AF_INET; sock_type = SOCK_RAW; sock_proto = IPPROTO_IGMP; if ((ecsockopt = socket(sock_domain,sock_type,sock_proto)) < 0) { printf("Error %d: Can't open socket.\n", errno); return 1; } else { printf("** Socket opened.\n"); } sockfd = ecsockopt; Then I set the TTL and Router Alert option: // Set the sent packets TTL if((ecsockopt = setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ip_multicast_ttl, sizeof(ip_multicast_ttl))) < 0) { printf("Error %d: Can't set TTL.\n", ecsockopt); return 1; } else { printf("** TTL set.\n"); } // Set the Router Alert if((ecsockopt = setsockopt(sockfd, IPPROTO_IP, IP_ROUTER_ALERT, &ip_router_alert, sizeof(ip_router_alert))) < 0) { printf("Error %d: Can't set Router Alert.\n", ecsockopt); return 1; } else { printf("** Router Alert set.\n"); } The setsockopt of IP_ROUTER_ALERT returns 0. After forging the packet, i send it with sendto in this way: // Send the packet if((bytes_num = sendto(sockfd, packet, packet_size, 0, (struct sockaddr*) &mgroup1_addr, sizeof(mgroup1_addr))) < 0) { printf("Error %d: Can't send Membership report message.\n", bytes_num); return 1; } else { printf("** Membership report message sent. (bytes=%d)\n",bytes_num); } The packet is sent, but the IP_ROUTER_ALERT option (checked with wireshark) is missing. Am i doing something wrong? is there some other methods to set the IP_ROUTER_ALERT option? Thanks in advance.

    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

  • Indexing with pointer C/C++

    - by Leavenotrace
    Hey I'm trying to write a program to carry out newtons method and find the roots of the equation exp(-x)-(x^2)+3. It works in so far as finding the root, but I also want it to print out the root after each iteration but I can't get it to work, Could anyone point out my mistake I think its something to do with my indexing? Thanks a million :) #include <stdio.h> #include <math.h> #include <malloc.h> //Define Functions: double evalf(double x) { double answer=exp(-x)-(x*x)+3; return(answer); } double evalfprime(double x) { double answer=-exp(-x)-2*x; return(answer); } double *newton(double initialrt,double accuracy,double *data) { double root[102]; data=root; int maxit = 0; root[0] = initialrt; for (int i=1;i<102;i++) { *(data+i)=*(data+i-1)-evalf(*(data+i-1))/evalfprime(*(data+i-1)); if(fabs(*(data+i)-*(data+i-1))<accuracy) { maxit=i; break; } maxit=i; } if((maxit+1==102)&&(fabs(*(data+maxit)-*(data+maxit-1))>accuracy)) { printf("\nMax iteration reached, method terminated"); } else { printf("\nMethod successful"); printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1,*(data+maxit)); } return(data); } int main() { double root,accuracy; double *data=(double*)malloc(sizeof(double)*102); printf("NEWTONS METHOD PROGRAMME:\nEquation: f(x)=exp(-x)-x^2+3=0\nMax No iterations=100\n\nEnter initial root estimate\n>> "); scanf("%lf",&root); _flushall(); printf("\nEnter accuracy required:\n>>"); scanf("%lf",&accuracy); *data= *newton(root,accuracy,data); printf("Iteration Root Error\n "); printf("%d %lf \n", 0,*(data)); for(int i=1;i<102;i++) { printf("%d %5.5lf %5.5lf\n", i,*(data+i),*(data+i)-*(data+i-1)); if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0) { break; } } getchar(); getchar(); free(data); return(0); }

    Read the article

  • adresse book with C programming, i have problem with library i think, couldn't complite my code

    - by osabri
    I've divided my code in small programm so it can be easy to excute /* ab_error.c : in case of errors following messages will be displayed */ #include "adressbook.h" static char *errormsg[] = { "", "\nNot enough space on disk", "\nCannot open file", "\nCannot read file", "\nCannot write file" }; void check(int error) { switch(error) { case 0: return; case 1: write_file(); case 2: case 3: case 4: system("cls"); fputs(errormsg[error], stderr); exit(error); } } 2nd /* ab_fileio.c : functions for file input/output */ include "adressbook.h" static char ab_file[] = "ADRESSBOOK.DAT"; //file to save the entries int read_file(void) { int error = 0; FILE *fp; ELEMENT *new_e, *last_e = NULL; DATA buffer; if( (fp = fopen(ab_file, "rb")) == NULL) return -1; //no file found while (fread(&buffer, sizeof(DATA), 1, fp) == 1) //reads one list element after another { if( (new_e = make_element()) == NULL) { error = 1; break; //not enough space } new_e->person = buffer; //copy data to new element new_e->next = NULL; if(hol.first == NULL) //list is empty? hol.first = new_e; //yes else last_e->next = new_e; //no last_e = new_e; ++hol.amount; } if( !error && !feof(fp) ) error = 3; //cannot read file fclose(fp); return error; } /-------------------------------/ int write_file(void) { int error = 0; FILE *fp; ELEMENT *p; if( (p = hol.first) == NULL) return 0; //list is empty if( (fp = fopen(ab_file, "wb")) == NULL) return 2; //cannot open while( p!= NULL) { if( fwrite(&p->person, sizeof(DATA), 1, fp) < 1) { error = 4; break; //cannot write } p = p->next; } fclose(fp); return error; } 3rd /* ab_list.c : functions to manipulate the list */ #include "adressbook.h" HOL hol = {0, NULL}; //global definition for head of list /* -------------------- */ ELEMENT *make_element(void) { return (ELEMENT *)malloc( sizeof(ELEMENT) ); } /* -------------------- */ int ins_element( DATA *newdata) { ELEMENT *new_e, *pre_p; if((new_e = make_element()) == NULL) return 1; new_e ->person = *newdata; // copy data to new element pre_p = search(new_e->person.family_name); if(pre_p == NULL) //no person in list { new_e->next = hol.first; //put it to the begin hol.first = new_e; } else { new_e->next = pre_p->next; pre_p->next = new_e; } ++hol.amount; return 0; } int erase_element( char name, char surname ) { return 0; } /* ---------------------*/ ELEMENT *search(char *name) { ELEMENT *sp, *retp; //searchpointer, returnpointer retp = NULL; sp = hol.first; while(sp != NULL && sp->person.family_name != name) { retp = sp; sp = sp->next; } return(retp); } 4th /* ab_screen.c : functions for printing information on screen */ #include "adressbook.h" #include <conio.h> #include <ctype.h> /* standard prompts for in- and output */ static char pgmname[] = "---- Oussama's Adressbook made in splendid C ----"; static char options[] = "\ 1: Enter new adress\n\n\ 2: Delete entry\n\n\ 3: Change entry\n\n\ 4: Print adress\n\n\ Esc: Exit\n\n\n\ Your choice . . .: "; static char prompt[] = "\ Name . . . .:\n\ Surname . . :\n\n\ Street . . .:\n\n\ House number:\n\n\ Postal code :\n\n\ Phone number:"; static char buttons[] = "\ <Esc> = cancel input <Backspace> = correct input\ <Return> = assume"; static char headline[] = "\ Name Surname Street House Postal code Phone number \n\ ------------------------------------------------------------------------"; static char further[] = "\ -------- continue with any key --------"; /* ---------------------------------- */ int menu(void) //show menu and read user input { int c; system ("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); printf("%s", options); while( (c = getch()) != ESC && (c < '1' || c > '4')) putch('\a'); return c; } /* ---------------------------------- */ int print_adr_book(void) //display adressbook { int line = 1; ELEMENT *p = hol.first; system("cls"); set_cur(0,20); puts(pgmname); set_cur(2,0); puts(headline); set_cur(5,0); while(p != NULL) //run through list and show entries { printf("%5d %-15s ",line, p->person.family_name); printf("%-12s %-15s ", p->person.given_name, p->person.street); printf("%-4d %-5d %-12d\n",p->person.house_number, p->person.postal_code, p->person.phone); p = p->next; if( p == NULL || ++line %16 == 1) //end of list or screen is full { set_cur(24,0); printf("%s",further); if( getch() == ESC) return 0; set_cur(5,0); scroll_up(0,5,24);//puts(headline); } } return 0; } /* -------------------------------------------*/ int make_entry(void) { char cache[50]; DATA newperson; ELEMENT *p; while(1) { system("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); puts("Please enter new data:"); set_cur(10,0); puts(prompt); set_cur(24,0); printf("%s",buttons); balken(10, 25, MAXL, ' ',0x70); //input name if(input(newperson.family_name, MAXL, ESC, CR) == ESC) return 0; balken(12,25, MAXL, ' ', 0x70); //surname if(input(newperson.given_name, MAXL, ESC, CR) == ESC) return 0; balken(14,25, 30, ' ', 0x70); //street if(input(newperson.street, 30, ESC, CR) == ESC) return 0; balken(16,25, 4, ' ',0x70); //housenumber if(input(cache, 4, ESC, CR) == ESC) return 0; newperson.house_number = atol(cache); //to string balken(18,25, 5, ' ',0x70); //postal code if(input(cache, 5, ESC, CR) == ESC) return 0; newperson.postal_code = atol(cache); //to string balken(20,25, 20, ' ',0x70); //phone number if(input(cache, 20, ESC, CR) == ESC) return 0; newperson.phone = atol(cache); //to string p = search(newperson.phone); if( p!= NULL && p->person.phone == newperson.phone) { set_cur(22,25); puts("phonenumber already exists!"); set_cur(24,0); printf("%s, further"); getch(); continue; } } } 5th /* adress_book_project.c : main program to create an adressbook */ /* copyrights by Oussama Sabri, June 2010 */ #include "adressbook.h" //project header file int main() { int rv, cmd; //return value, user command if ( (rv = read_file() ) == -1) // no data saved yet rv = make_entry(); check(rv); //prompts an error and quits program on disfunction do { switch (cmd = menu())//calls menu and gets user input back { case '1': rv = make_entry(); break; case '2': //delete entry case '3': //changes entry rv = change_entry(cmd); break; case '4': //prints adressbook on screen rv = print_adr_book(); break; case ESC: //end of program system ("cls"); rv = 0; break; } }while(cmd!= ESC); check ( write_file() ); //save adressbook return 0; } 6th /* Getcb.c --> Die Funktion getcb() liefert die naechste * * Tastatureingabe (ruft den BIOS-INT 0x16 auf). * * Return-Wert: * * ASCII-Code bzw. erweiterter Code + 256 */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> int getcb(void) { union REGS intregs; intregs.h.ah = 0; // Subfunktion 0: ein Zeichen // von der Tastatur lesen. int86( 0x16, &intregs, &intregs); if( intregs.h.al != 0) // Falls ASCII-Zeichen, return (intregs.h.al); // dieses zurueckgeben. else // Sonst den erweiterten return (intregs.h.ah + 0x100); // Code + 256 } 7th /* PUTCB.C --> enthaelt die Funktionen * * - putcb() * * - putcb9() * * - balken() * * - input() * * * * Es werden die Funktionen 9 und 14 des Video-Interrupts * * (ROM-BIOS-Interrupt 0x10) verwendet. * * * * Die Prototypen dieser Funktionen stehen in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #define VIDEO_INT 0x10 /*---------------------------------------------------------------- * putcb(c) gibt das Zeichen auf der aktuellen Cursor-Position * am Bildschirm aus. Der Cursor wird versetzt. * Steuerzeichen Back-Space, CR, LF und BELL werden * ausgefuehrt. * Return-Wert: keiner */ void putcb(unsigned char c) /* Gibt das Zeichen in c auf */ { /* den Bildschirm aus. */ union REGS intregs; intregs.h.ah = 14; /* Subfunktion 14 ("Teletype") */ intregs.h.al = c; intregs.h.bl = 0xf; /* Vordergrund-Farbe im */ /* Grafik-Modus. */ int86(VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * putcb9(c,count,mode) gibt das Zeichen in c count-mal im * angegebenen Modus auf der aktuellen * Cursor-Position am Bildschirm aus. * Der Cursor wird nicht versetzt. * * Return-Wert: keiner */ void putcb9( unsigned char c, /* das Zeichen */ unsigned count, /* die Anzahl */ unsigned mode ) /* Low-Byte: das Atrribut */ { /* High-Byte: die Bildschirmseite*/ union REGS intregs; intregs.h.ah = 9; /* Subfunktion 9 des Int 0x10 */ intregs.h.al = c; intregs.x.bx = mode; intregs.x.cx = count; int86( VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * balken() positioniert den Cursor und zeichnet einen Balken, * wobei Position, L„nge, Fllzeichen und Attribut * als Argumente bergeben werden. * Der Cursor bleibt auf der ersten Position im Balken. */ void balken( unsigned int zeile, /* Start-Position */ unsigned int spalte, unsigned int laenge, /* Laenge des Balkens */ unsigned char c, /* Fuellzeichen */ unsigned int modus) /* Low-Byte: Attribut */ /* High-Byte: Bildschirmseite */ { union REGS intregs; intregs.h.ah = 2; /* Cursor auf der angegebenen */ intregs.h.dh = zeile; /* Bildschirmseite versetzen. */ intregs.h.dl = spalte; intregs.h.bh = (modus >> 8); int86(VIDEO_INT, &intregs, &intregs); putcb9(c, laenge, modus); /* Balken ausgeben. */ } /*---------------------------------------------------------------- * input() liest Zeichen von der Tastatur ein und haengt '\0' an. * Mit Backspace kann die Eingabe geloescht werden. * Das Attribut am Bildschirm bleibt erhalten. * * Argumente: 1. Zeiger auf den Eingabepuffer. * 2. Anzahl maximal einzulesender Zeichen. * 3. Die optionalen Argumente: Zeichen, mit denen die * Eingabe abgebrochen werden kann. * Diese Liste muá mit CR = '\r' enden! * Return-Wert: Das Zeichen, mit dem die Eingabe abgebrochen wurde. */ #include <stdarg.h> int getcb( void); /* Zum Lesen der Tastatur */ int input(char *puffer, int max,... ) { int c; /* aktuelles Zeichen */ int breakc; /* Abruchzeichen */ int nc = 0; /* Anzahl eingelesener Zeichen */ va_list argp; /* Zeiger auf die weiteren Arumente */ while(1) { *puffer = '\0'; va_start(argp, max); /* argp initialisieren */ c = getcb(); do /* Mit Zeichen der Abbruchliste vergleichen */ if(c == (breakc = va_arg(argp,int)) ) return(breakc); while( breakc != '\r' ); va_end( argp); if( c == '\b' && nc > 0) /* Backspace? */ { --nc; --puffer; putcb(c); putcb(' '); putcb(c); } else if( c >= 32 && c <= 255 && nc < max ) { ++nc; *puffer++ = c; putcb(c); } else if( nc == max) putcb('\7'); /* Ton ausgeben */ } } 8th /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* BIO.H --> Enthaelt die Prototypen der BIOS-Funktionen. */ /* --- Funktionen in VIDEO.C --- */ extern void scroll_up(int anzahl, int anf_zeile,int end_zeile); extern void scroll_down(int anzahl, int anf_zeile, int end_zeile); extern void set_cur(int zeile, int spalte); extern void get_cur(int *zeile, int *spalte); extern void cls(void); extern int get_screen_page(void); extern void set_screen_page(int page); /* --- Funktionen in GETCB.C / PUTCB.C --- */ extern int getcb(void); extern void putcb(int c); extern void putcb9(int c, unsigned count, unsigned modus); extern void balken(int zeile, int spalte, int laenge, int c, unsigned modus); extern int input(char *puffer, int max,... ); need your help, can't find my mistakes:((

    Read the article

  • Address book with C programming; cannot compile my code.

    - by osabri
    I've divided my code into small programs so it can be easy to excute /* ab_error.c : in case of errors following messages will be displayed */ #include "adressbook.h" static char *errormsg[] = { "", "\nNot enough space on disk", "\nCannot open file", "\nCannot read file", "\nCannot write file" }; void check(int error) { switch(error) { case 0: return; case 1: write_file(); case 2: case 3: case 4: system("cls"); fputs(errormsg[error], stderr); exit(error); } } 2nd /* ab_fileio.c : functions for file input/output */ #include "adressbook.h" static char ab_file[] = "ADRESSBOOK.DAT"; //file to save the entries int read_file(void) { int error = 0; FILE *fp; ELEMENT *new_e, *last_e = NULL; DATA buffer; if( (fp = fopen(ab_file, "rb")) == NULL) return -1; //no file found while (fread(&buffer, sizeof(DATA), 1, fp) == 1) //reads one list element after another { if( (new_e = make_element()) == NULL) { error = 1; break; //not enough space } new_e->person = buffer; //copy data to new element new_e->next = NULL; if(hol.first == NULL) //list is empty? hol.first = new_e; //yes else last_e->next = new_e; //no last_e = new_e; ++hol.amount; } if( !error && !feof(fp) ) error = 3; //cannot read file fclose(fp); return error; } /*-------------------------------*/ int write_file(void) { int error = 0; FILE *fp; ELEMENT *p; if( (p = hol.first) == NULL) return 0; //list is empty if( (fp = fopen(ab_file, "wb")) == NULL) return 2; //cannot open while( p!= NULL) { if( fwrite(&p->person, sizeof(DATA), 1, fp) < 1) { error = 4; break; //cannot write } p = p->next; } fclose(fp); return error; } 3rd /* ab_list.c : functions to manipulate the list */ #include "adressbook.h" HOL hol = {0, NULL}; //global definition for head of list /* -------------------- */ ELEMENT *make_element(void) { return (ELEMENT *)malloc( sizeof(ELEMENT) ); } /* -------------------- */ int ins_element( DATA *newdata) { ELEMENT *new_e, *pre_p; if((new_e = make_element()) == NULL) return 1; new_e ->person = *newdata; // copy data to new element pre_p = search(new_e->person.family_name); if(pre_p == NULL) //no person in list { new_e->next = hol.first; //put it to the begin hol.first = new_e; } else { new_e->next = pre_p->next; pre_p->next = new_e; } ++hol.amount; return 0; } int erase_element( char name, char surname ) { return 0; } /* ---------------------*/ ELEMENT *search(char *name) { ELEMENT *sp, *retp; //searchpointer, returnpointer retp = NULL; sp = hol.first; while(sp != NULL && sp->person.family_name != name) { retp = sp; sp = sp->next; } return(retp); } 4th /* ab_screen.c : functions for printing information on screen */ #include "adressbook.h" #include <conio.h> #include <ctype.h> /* standard prompts for in- and output */ static char pgmname[] = "---- Oussama's Adressbook made in splendid C ----"; static char options[] = "\ 1: Enter new adress\n\n\ 2: Delete entry\n\n\ 3: Change entry\n\n\ 4: Print adress\n\n\ Esc: Exit\n\n\n\ Your choice . . .: "; static char prompt[] = "\ Name . . . .:\n\ Surname . . :\n\n\ Street . . .:\n\n\ House number:\n\n\ Postal code :\n\n\ Phone number:"; static char buttons[] = "\ <Esc> = cancel input <Backspace> = correct input\ <Return> = assume"; static char headline[] = "\ Name Surname Street House Postal code Phone number \n\ ------------------------------------------------------------------------"; static char further[] = "\ -------- continue with any key --------"; /* ---------------------------------- */ int menu(void) //show menu and read user input { int c; system ("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); printf("%s", options); while( (c = getch()) != ESC && (c < '1' || c > '4')) putch('\a'); return c; } /* ---------------------------------- */ int print_adr_book(void) //display adressbook { int line = 1; ELEMENT *p = hol.first; system("cls"); set_cur(0,20); puts(pgmname); set_cur(2,0); puts(headline); set_cur(5,0); while(p != NULL) //run through list and show entries { printf("%5d %-15s ",line, p->person.family_name); printf("%-12s %-15s ", p->person.given_name, p->person.street); printf("%-4d %-5d %-12d\n",p->person.house_number, p->person.postal_code, p->person.phone); p = p->next; if( p == NULL || ++line %16 == 1) //end of list or screen is full { set_cur(24,0); printf("%s",further); if( getch() == ESC) return 0; set_cur(5,0); scroll_up(0,5,24);//puts(headline); } } return 0; } /* -------------------------------------------*/ int make_entry(void) { char cache[50]; DATA newperson; ELEMENT *p; while(1) { system("cls"); set_cur(0,20); puts(pgmname); set_cur(6,0); puts("Please enter new data:"); set_cur(10,0); puts(prompt); set_cur(24,0); printf("%s",buttons); balken(10, 25, MAXL, ' ',0x70); //input name if(input(newperson.family_name, MAXL, ESC, CR) == ESC) return 0; balken(12,25, MAXL, ' ', 0x70); //surname if(input(newperson.given_name, MAXL, ESC, CR) == ESC) return 0; balken(14,25, 30, ' ', 0x70); //street if(input(newperson.street, 30, ESC, CR) == ESC) return 0; balken(16,25, 4, ' ',0x70); //housenumber if(input(cache, 4, ESC, CR) == ESC) return 0; newperson.house_number = atol(cache); //to string balken(18,25, 5, ' ',0x70); //postal code if(input(cache, 5, ESC, CR) == ESC) return 0; newperson.postal_code = atol(cache); //to string balken(20,25, 20, ' ',0x70); //phone number if(input(cache, 20, ESC, CR) == ESC) return 0; newperson.phone = atol(cache); //to string p = search(newperson.phone); if( p!= NULL && p->person.phone == newperson.phone) { set_cur(22,25); puts("phonenumber already exists!"); set_cur(24,0); printf("%s, further"); getch(); continue; } } } 5th /* adress_book_project.c : main program to create an adressbook */ /* copyrights by Oussama Sabri, June 2010 */ #include "adressbook.h" //project header file int main() { int rv, cmd; //return value, user command if ( (rv = read_file() ) == -1) // no data saved yet rv = make_entry(); check(rv); //prompts an error and quits program on disfunction do { switch (cmd = menu())//calls menu and gets user input back { case '1': rv = make_entry(); break; case '2': //delete entry case '3': //changes entry rv = change_entry(cmd); break; case '4': //prints adressbook on screen rv = print_adr_book(); break; case ESC: //end of program system ("cls"); rv = 0; break; } }while(cmd!= ESC); check ( write_file() ); //save adressbook return 0; } 6th /* Getcb.c --> Die Funktion getcb() liefert die naechste * * Tastatureingabe (ruft den BIOS-INT 0x16 auf). * * Return-Wert: * * ASCII-Code bzw. erweiterter Code + 256 */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> int getcb(void) { union REGS intregs; intregs.h.ah = 0; // Subfunktion 0: ein Zeichen // von der Tastatur lesen. int86( 0x16, &intregs, &intregs); if( intregs.h.al != 0) // Falls ASCII-Zeichen, return (intregs.h.al); // dieses zurueckgeben. else // Sonst den erweiterten return (intregs.h.ah + 0x100); // Code + 256 } 7th /* PUTCB.C --> enthaelt die Funktionen * * - putcb() * * - putcb9() * * - balken() * * - input() * * * * Es werden die Funktionen 9 und 14 des Video-Interrupts * * (ROM-BIOS-Interrupt 0x10) verwendet. * * * * Die Prototypen dieser Funktionen stehen in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #define VIDEO_INT 0x10 /*---------------------------------------------------------------- * putcb(c) gibt das Zeichen auf der aktuellen Cursor-Position * am Bildschirm aus. Der Cursor wird versetzt. * Steuerzeichen Back-Space, CR, LF und BELL werden * ausgefuehrt. * Return-Wert: keiner */ void putcb(unsigned char c) /* Gibt das Zeichen in c auf */ { /* den Bildschirm aus. */ union REGS intregs; intregs.h.ah = 14; /* Subfunktion 14 ("Teletype") */ intregs.h.al = c; intregs.h.bl = 0xf; /* Vordergrund-Farbe im */ /* Grafik-Modus. */ int86(VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * putcb9(c,count,mode) gibt das Zeichen in c count-mal im * angegebenen Modus auf der aktuellen * Cursor-Position am Bildschirm aus. * Der Cursor wird nicht versetzt. * * Return-Wert: keiner */ void putcb9( unsigned char c, /* das Zeichen */ unsigned count, /* die Anzahl */ unsigned mode ) /* Low-Byte: das Atrribut */ { /* High-Byte: die Bildschirmseite*/ union REGS intregs; intregs.h.ah = 9; /* Subfunktion 9 des Int 0x10 */ intregs.h.al = c; intregs.x.bx = mode; intregs.x.cx = count; int86( VIDEO_INT, &intregs, &intregs); } /*---------------------------------------------------------------- * balken() positioniert den Cursor und zeichnet einen Balken, * wobei Position, L„nge, Fllzeichen und Attribut * als Argumente bergeben werden. * Der Cursor bleibt auf der ersten Position im Balken. */ void balken( unsigned int zeile, /* Start-Position */ unsigned int spalte, unsigned int laenge, /* Laenge des Balkens */ unsigned char c, /* Fuellzeichen */ unsigned int modus) /* Low-Byte: Attribut */ /* High-Byte: Bildschirmseite */ { union REGS intregs; intregs.h.ah = 2; /* Cursor auf der angegebenen */ intregs.h.dh = zeile; /* Bildschirmseite versetzen. */ intregs.h.dl = spalte; intregs.h.bh = (modus >> 8); int86(VIDEO_INT, &intregs, &intregs); putcb9(c, laenge, modus); /* Balken ausgeben. */ } /*---------------------------------------------------------------- * input() liest Zeichen von der Tastatur ein und haengt '\0' an. * Mit Backspace kann die Eingabe geloescht werden. * Das Attribut am Bildschirm bleibt erhalten. * * Argumente: 1. Zeiger auf den Eingabepuffer. * 2. Anzahl maximal einzulesender Zeichen. * 3. Die optionalen Argumente: Zeichen, mit denen die * Eingabe abgebrochen werden kann. * Diese Liste muá mit CR = '\r' enden! * Return-Wert: Das Zeichen, mit dem die Eingabe abgebrochen wurde. */ #include <stdarg.h> int getcb( void); /* Zum Lesen der Tastatur */ int input(char *puffer, int max,... ) { int c; /* aktuelles Zeichen */ int breakc; /* Abruchzeichen */ int nc = 0; /* Anzahl eingelesener Zeichen */ va_list argp; /* Zeiger auf die weiteren Arumente */ while(1) { *puffer = '\0'; va_start(argp, max); /* argp initialisieren */ c = getcb(); do /* Mit Zeichen der Abbruchliste vergleichen */ if(c == (breakc = va_arg(argp,int)) ) return(breakc); while( breakc != '\r' ); va_end( argp); if( c == '\b' && nc > 0) /* Backspace? */ { --nc; --puffer; putcb(c); putcb(' '); putcb(c); } else if( c >= 32 && c <= 255 && nc < max ) { ++nc; *puffer++ = c; putcb(c); } else if( nc == max) putcb('\7'); /* Ton ausgeben */ } } 8th /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* Video.c --> Enthaelt die Funktionen * cls(), * scroll_up(), scroll_down(), * set_cur(), get_cur(), * set_screen_page(), get_screen_page() * * Die Prototypen dieser Funktionen befinden sich in BIO.H */ /* Hinweis: Es muss ein DOS-Compiler verwendet werden. * * (z.B. der GNU-Compiler fuer DOS auf der CD) */ #include <dos.h> #include "bio.h" #define VIDEO_INT 0x10 typedef unsigned char BYTE; void scroll_up( int anzahl, int anf_zeile, int end_zeile) { /* Fenster hoch rollen. */ union REGS intregs; intregs.x.ax = 0x600 + anzahl; /* Subfunktion AH = 6, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void scroll_down( int anzahl, int anf_zeile, int end_zeile) { /* Fenster runter rollen. */ union REGS intregs; intregs.x.ax = 0x700 + anzahl; /* Subfunktion AH = 7, */ /* AL = Anzahl Zeilen. */ intregs.x.cx = anf_zeile << 8; /* CH=anf_zeile, cl=0 */ intregs.x.dx = (end_zeile <<8) | 79; /* DH=end_zeile,DL=79 */ intregs.h.bh = 7; /* normales Attribut */ int86(VIDEO_INT, &intregs, &intregs); } void set_cur( int zeile, int spalte) /* versetzt den Cursor */ { /* der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 2; intregs.h.dh = (BYTE)zeile; intregs.h.dl = (BYTE)spalte; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); } void get_cur(int *zeile, int *spalte) /* holt die Cursor- */ { /* Position der aktuellen Bildschirmseite.*/ union REGS intregs; intregs.h.ah = 3; intregs.h.bh = (BYTE)get_screen_page(); int86(VIDEO_INT, &intregs, &intregs); *zeile = (unsigned)intregs.h.dh; *spalte = (unsigned)intregs.h.dl; } void cls(void) { scroll_up(0,0,24); /* Gesamten Bildschirm loeschen. */ set_cur(0,0); /* Cursor in Home-Position. */ } int get_screen_page(void) /* Aktuelle Bildschirmseite holen.*/ { union REGS intregs; intregs.h.ah = 15; /* Subfunktion AH = 15: */ /* Bildschirm-Modus feststellen. */ int86(VIDEO_INT, &intregs, &intregs); return (intregs.h.bh); } void set_screen_page(int seite) /* setzt die aktive Seite des */ { /* Bildschirmpuffers auf die */ /* angegebene Seite. */ union REGS intregs; intregs.x.ax = 0x500 + seite; /* Subfunktion AH = 5 */ int86(VIDEO_INT, &intregs, &intregs); } /* ------------------------------------------------------------- Ein kleines Testprogramm : */ /* #include <stdio.h> int main() { cls(); set_cur(23, 0); printf("Weiter mit <Return>\n"); set_cur(12, 20); printf("Ein Test!\n"); getchar(); scroll_up(3, 5, 20); getchar(); scroll_down(6, 5, 20); getchar(); set_screen_page(1); printf("\nAuf der 2. Seite !\n"); getchar(); set_screen_page(0); set_cur(0,0); printf("\nWieder auf der 1. Seite !\n"); getchar(); cls(); return 0; } */ /* BIO.H --> Enthaelt die Prototypen der BIOS-Funktionen. */ /* --- Funktionen in VIDEO.C --- */ extern void scroll_up(int anzahl, int anf_zeile,int end_zeile); extern void scroll_down(int anzahl, int anf_zeile, int end_zeile); extern void set_cur(int zeile, int spalte); extern void get_cur(int *zeile, int *spalte); extern void cls(void); extern int get_screen_page(void); extern void set_screen_page(int page); /* --- Funktionen in GETCB.C / PUTCB.C --- */ extern int getcb(void); extern void putcb(int c); extern void putcb9(int c, unsigned count, unsigned modus); extern void balken(int zeile, int spalte, int laenge, int c, unsigned modus); extern int input(char *puffer, int max,... ); need your help, can't find my mistakes:((

    Read the article

  • Thread scheduling C

    - by MRP
    include <pthread.h> include <stdio.h> include <stdlib.h> #define NUM_THREADS 4 #define TCOUNT 5 #define COUNT_LIMIT 13 int done = 0; int count = 0; int thread_ids[4] = {0,1,2,3}; int thread_runtime[4] = {0,5,4,1}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; long run_time = thread_runtime[my_id]; if (my_id==2 && done ==0) { for(i=0; i< 5 ; i++) { if( i==4 ){done =1;} pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", my_id, count); pthread_mutex_unlock(&count_mutex); } } if (my_id==3 && done==1) { for(i=0; i< 4 ; i++) { if(i == 3 ){ done = 2;} pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", my_id, count); pthread_mutex_unlock(&count_mutex); } } if (my_id==4&& done == 2) { for(i=0; i< 8 ; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\n",my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", my_id, count); pthread_mutex_unlock(&count_mutex); } } pthread_exit(NULL); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\n", my_id); pthread_mutex_lock(&count_mutex); if (count<COUNT_LIMIT) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3, t4=4; pthread_t threads[4]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, NULL); pthread_cond_init (&count_threshold_cv, NULL); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); pthread_create(&threads[3], &attr, inc_count, (void *)t4); for (i=0; i<NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf ("Main(): Waited on %d threads. Done.\n", NUM_THREADS); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(NULL); } so this code creates 4 threads. thread 1 keeps track of the count value while the other 3 increment the count value. the run time is the number of times the thread will increment the count value. I have a done value that allows the first thread to increment the count value first until its run time is up.. so its like a First Come First Serve. my question is, is there a better way of implementing this? I have read about SCHED_FIFO or SCHED_RR.. I guess I dont know how to implement them into this code or if it can be.

    Read the article

  • C: How come an array's address is equal to its value?

    - by Alexandre
    In the following bit of code, pointer values and pointer addresses differ as expected. But array values and addresses don't! How can this be? Output my_array = 0022FF00 &my_array = 0022FF00 pointer_to_array = 0022FF00 &pointer_to_array = 0022FEFC ... #include <stdio.h> int main() { char my_array[100] = "some cool string"; printf("my_array = %p\n", my_array); printf("&my_array = %p\n", &my_array); char *pointer_to_array = my_array; printf("pointer_to_array = %p\n", pointer_to_array); printf("&pointer_to_array = %p\n", &pointer_to_array); printf("Press ENTER to continue...\n"); getchar(); return 0; }

    Read the article

  • Test of procedure is fine but when called from a menu gives uninitialized errors. C

    - by Delfic
    The language is portuguese, but I think you get the picture. My main calls only the menu function (the function in comment is the test which works). In the menu i introduce the option 1 which calls the same function. But there's something wrong. If i test it solely on the input: (1/1)x^2 //it reads the polinomyal (2/1) //reads the rational and returns 4 (you can guess what it does, calculates the value of an instace of x over a rational) My polinomyals are linear linked lists with a coeficient (rational) and a degree (int) int main () { menu_interactivo (); // instanciacao (); return 0; } void menu_interactivo(void) { int i; do{ printf("1. Instanciacao de um polinomio com um escalar\n"); printf("2. Multiplicacao de um polinomio por um escalar\n"); printf("3. Soma de dois polinomios\n"); printf("4. Multiplicacao de dois polinomios\n"); printf("5. Divisao de dois polinomios\n"); printf("0. Sair\n"); scanf ("%d", &i); switch (i) { case 0: exit(0); break; case 1: instanciacao (); break; case 2: multiplicacao_esc (); break; case 3: somar_pol (); break; case 4: multiplicacao_pol (); break; case 5: divisao_pol (); break; default:printf("O numero introduzido nao e valido!\n"); } } while (i != 0); } When i call it with the menu, with the same input, it does not stop reading the polinomyal (I know this because it does not ask me for the rational as on the other example) I've run it with valgrind --track-origins=yes returning the following: ==17482== Memcheck, a memory error detector ==17482== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==17482== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info ==17482== Command: ./teste ==17482== 1. Instanciacao de um polinomio com um escalar 2. Multiplicacao de um polinomio por um escalar 3. Soma de dois polinomios 4. Multiplicacao de dois polinomios 5. Divisao de dois polinomios 0. Sair 1 Introduza um polinomio na forma (n0/d0)x^e0 + (n1/d1)x^e1 + ... + (nk/dk)^ek, com ei > e(i+1): (1/1)x^2 ==17482== Conditional jump or move depends on uninitialised value(s) ==17482== at 0x401126: simplifica_f (fraccoes.c:53) ==17482== by 0x4010CB: le_f (fraccoes.c:30) ==17482== by 0x400CDA: le_pol (polinomios.c:156) ==17482== by 0x400817: instanciacao (t4.c:14) ==17482== by 0x40098C: menu_interactivo (t4.c:68) ==17482== by 0x4009BF: main (t4.c:86) ==17482== Uninitialised value was created by a stack allocation ==17482== at 0x401048: le_f (fraccoes.c:19) ==17482== ==17482== Conditional jump or move depends on uninitialised value(s) ==17482== at 0x400D03: le_pol (polinomios.c:163) ==17482== by 0x400817: instanciacao (t4.c:14) ==17482== by 0x40098C: menu_interactivo (t4.c:68) ==17482== by 0x4009BF: main (t4.c:86) ==17482== Uninitialised value was created by a stack allocation ==17482== at 0x401048: le_f (fraccoes.c:19) ==17482== I will now give you the functions which are called void le_pol (pol *p) { fraccao f; int e; char c; printf ("Introduza um polinomio na forma (n0/d0)x^e0 + (n1/d1)x^e1 + ... + (nk/dk)^ek,\n"); printf("com ei > e(i+1):\n"); *p = NULL; do { le_f (&f); getchar(); getchar(); scanf ("%d", &e); if (f.n != 0) *p = add (*p, f, e); c = getchar (); if (c != '\n') { getchar(); getchar(); } } while (c != '\n'); } void instanciacao (void) { pol p1; fraccao f; le_pol (&p1); printf ("Insira uma fraccao na forma (n/d):\n"); le_f (&f); escreve_f(inst_esc_pol(p1, f)); } void le_f (fraccao *f) { int n, d; getchar (); scanf ("%d", &n); getchar (); scanf ("%d", &d); getchar (); assert (d != 0); *f = simplifica_f(cria_f(n, d)); } simplifica_f simplifies a rational and cria_f creates a rationa given the numerator and the denominator Can someone help me please? Thanks in advance. If you want me to provide some tests, just post it. See ya.

    Read the article

  • option page form in my wordpress theme [migrated]

    - by Templategraphy
    here its is my option page code containing no of fields like logo, slider after filling all the information in option page form i want to things After submitting all the form details save information must retain there. Using get_option() extract each input tag value and show that value in front hand like slider image, slider heading, slider description OPTION PAGE CODE: <?php class MySettingsPage { private $options; public function __construct() { add_action( 'admin_menu', array( $this, 'bguru_register_options_page' ) ); add_action( 'admin_init', array( $this, 'bguru_register_settings' ) ); } public function bguru_register_options_page() { // This page will be under "Settings" add_theme_page('Business Guru Options', 'Theme Customizer', 'edit_theme_options', 'bguru-options', array( $this, 'bguru_options_page') ); } public function bguru_options_page() { // Set class property $this->options = get_option( 'bguru_logo' ); $this->options = get_option( 'bguru_vimeo' ); $this->options = get_option( 'bguru_slide_one_image' ); $this->options = get_option( 'bguru_slide_one_heading' ); $this->options = get_option( 'bguru_slide_one_text' ); $this->options = get_option( 'bguru_slogan_heading' ); $this->options = get_option( 'bguru_slogan_description' ); ?> <div class="wrap"> <?php screen_icon(); ?> <h1>Business Guru Options</h1> <form method="post" action="options.php"> <table class="form-table"> <?php // This prints out all hidden setting fields settings_fields( 'defaultbg' ); do_settings_sections( 'defaultbg' ); submit_button(); ?> </table> </form> </div> <?php } /** * Register and add settings */ public function bguru_register_settings() { register_setting('defaultbg','bguru_logo', array( $this, 'sanitize' ) ); register_setting('defaultbg', 'bguru_vimeo', array( $this, 'sanitize' )); register_setting('defaultbg', 'bguru_slide_one_image', array( $this, 'sanitize' )); register_setting('defaultbg', 'bguru_slide_one_heading', array( $this, 'sanitize' )); register_setting('defaultbg', 'bguru_slide_one_text', array( $this, 'sanitize' )); register_setting('defaultbg', 'bguru_slogan_heading', array( $this, 'sanitize' )); register_setting('defaultbg', 'bguru_slogan_description', array( $this, 'sanitize' )); add_settings_section( 'setting_section_id', // ID '<h2>General</h2>', array( $this, 'print_section_info' ), // Callback 'defaultbg' // Page ); add_settings_field( 'bguru_logo', // ID '<label for="bguru_logo">Logo</label>', // Title array($this,'logo_callback' ), // Callback 'defaultbg', // Page 'setting_section_id'// Section ); add_settings_field( 'bguru_vimeo', // ID 'Vimeo', // Vimeo array( $this, 'socialv_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); add_settings_field( 'bguru_slide_one_image', // ID 'Slide 1 Image', // Slide 1 Image array( $this, 'slider1img_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); add_settings_field( 'bguru_slide_one_heading', // ID 'Slide 1 Heading', // Slide 1 Heading array( $this, 'slider1head_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); add_settings_field( 'bguru_slide_one_text', // ID 'Slide 1 Description', // Slide 1 Description array( $this, 'slider1text_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); add_settings_field( 'bguru_slogan_heading', // ID 'Slogan Heading', // Slogan Heading array( $this, 'slogan_head_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); add_settings_field( 'bguru_slogan_description', // ID 'Slogan Container', // Slogan Container array( $this, 'slogan_descr_callback' ), // Callback 'defaultbg', // Page 'setting_section_id' // Section ); } public function sanitize( $input ) { $new_input = array(); if( isset( $input['bguru_logo'] ) ) $new_input['bguru_logo'] = sanitize_text_field( $input['bguru_logo'] ); if( isset( $input['bguru_vimeo'] ) ) $new_input['bguru_vimeo'] = sanitize_text_field( $input['bguru_vimeo'] ); if( isset( $input['bguru_slide_one_image'] ) ) $new_input['bguru_slide_one_image'] = sanitize_text_field( $input['bguru_slide_one_image'] ); if( isset( $input['bguru_slide_one_heading'] ) ) $new_input['bguru_slide_one_heading'] = sanitize_text_field( $input['bguru_slide_one_heading'] ); if( isset( $input['bguru_slide_one_text'] ) ) $new_input['bguru_slide_one_text'] = sanitize_text_field( $input['bguru_slide_one_text'] ); if( isset( $input['bguru_slogan_heading'] ) ) $new_input['bguru_slogan_heading'] = sanitize_text_field( $input['bguru_slogan_heading'] ); if( isset( $input['bguru_slogan_description'] ) ) $new_input['bguru_slogan_description'] = sanitize_text_field( $input['bguru_slogan_description'] ); return $new_input; } public function print_section_info() { print 'Enter your settings below:'; } public function logo_callback() { printf( '<input type="text" id="bguru_logo" size="50" name="bguru_logo" value="%s" />', isset( $this->options['bguru_logo'] ) ? esc_attr( $this->options['bguru_logo']) : '' ); } public function socialv_callback() { printf( '<input type="text" id="bguru_vimeo" size="50" name="bguru_vimeo" value="%s" />', isset( $this->options['bguru_vimeo'] ) ? esc_attr( $this->options['bguru_vimeo']) : '' ); } public function slider1img_callback() { printf( '<input type="text" id="bguru_slide_one_image" size="50" name="bguru_slide_one_image" value="%s" />', isset( $this->options['bguru_slide_one_image'] ) ? esc_attr( $this->options['bguru_slide_one_image']) : '' ); } public function slider1head_callback() { printf( '<input type="text" id="bguru_slide_one_heading" size="50" name="bguru_slide_one_heading" value="%s" />', isset( $this->options['bguru_slide_one_heading'] ) ? esc_attr( $this->options['bguru_slide_one_heading']) : '' ); } public function slider1text_callback() { printf( '<input type="text" id="bguru_slide_one_text" size="50" name="bguru_slide_one_text" value="%s" />', isset( $this->options['bguru_slide_one_text'] ) ? esc_attr( $this->options['bguru_slide_one_text']) : '' ); } public function slogan_head_callback() { printf( '<input type="text" id="bguru_slogan_heading" size="50" name="bguru_slogan_heading" value="%s" />', isset( $this->options['bguru_slogan_heading'] ) ? esc_attr( $this->options['bguru_slogan_heading']) : '' ); } public function slogan_descr_callback() { printf( '<input type="text" id="bguru_slogan_description" size="50" name="bguru_slogan_description" value="%s" />', isset( $this->options['bguru_slogan_description'] ) ? esc_attr( $this->options['bguru_slogan_description']) : '' ); } } if( is_admin() ) $my_settings_page = new MySettingsPage(); here its my header.php code where i display all the information of option form $bguru_logo_image = get_option('bguru_logo'); if (!empty($bguru_logo_image)) { echo '<div id="logo"><a href="' . home_url() . '"><img src="' . $bguru_logo_image . '" width="218" alt="logo" /></a></div><!--/ #logo-->'; } else { echo '<div id="logo"><a href="' . home_url() . '"><h1>'. get_bloginfo('name') . '</h1></a></div><!--/ #logo-->'; }?> $bguru_social_vimeo = get_option('bguru_vimeo'); if (!empty($bguru_social_vimeo)) { echo '<li class="vimeo"><a target="_blank" href="'.$bguru_social_vimeo.'">Vimeo</a></li>'; }?> same as for slider image, slider heading, slider description please suggest some solutions

    Read the article

  • Solaris ????????????????

    - by Homma
    ???? ???????????? CPU ?????????????????????????????????? OS ??????????????????????????????????????????????CPU ??????????????????? CPU ???????????????????????????????????????????????????????????????????????????? CPU ??????????????????????????????????? CPU ???????????????????????? CPU ????????????????????????? CPU ?????????????????????????????????????????????????????????????????????????????DTrace ????????????????? ?? ????????????????????????????????????????????? CPU ????????????????? # cat prog01.c int main() { while(1) {}; } # gcc prog01.c -o prog01 ?????????????????????pbind ?????????? CPU 1 ??????psradm ????????? CPU 1 ?????????????????????????? CPU 1 ?????????????? # ./prog01 & [1] 3247 # pbind -b 1 3247 process id 3247: was not bound, now 1 # psradm -i 1 # psrinfo 1 1 no-intr since 09/24/2012 05:46:25 ????????? Solaris 10 8/11 ????????? # cat /etc/release Oracle Solaris 10 8/11 s10x_u10wos_17b X86 Copyright (c) 1983, 2011, Oracle and/or its affiliates. All rights reserved. Assembled 23 August 2011 ????????????????????????? DTrace ??????????????(??????)???????????????????????????? preempt ??????????????????? DTrace ????????????????????????????????????????????????????????????????????????????? # dtrace -qn 'BEGIN{ ts = timestamp; } sched:::preempt/pid == $target/ { printf("%d\n",timestamp - ts); ts = timestamp }' -p 3247 ?????????????????????? 200 ????????????????????? # dtrace -qn 'BEGIN{ ts = timestamp; } sched:::preempt/pid == $target/ { printf("%d\n",timestamp - ts); ts = timestamp }' -p 3247 3547836 199976558 200030610 199964001 200001048 199999666 200021432 ???????????? 200 ????? CPU ????????????? CPU ????????????????????? ??????? CPU 1 ????????????? prog01 ?????????????????????????????????? prog01 ?????????????????????????????????????????????????????????? 200 ??????????????? ????????????????????????? ?????????????????????????????? DTrace ????????DTrace ???????????????????????????????????????????????????????????????????? # dtrace -qn 'sched:::preempt/pid == $target/ { printf("%d\n", ((tsproc_t*)curthread->t_cldata)->ts_timeleft); }' -p 3247 ??????????????????????????????? 1/100 ???????? 200 ????????????????? # dtrace -qn 'sched:::preempt/pid == $target/ { printf("%d\n", ((tsproc_t*)curthread->t_cldata)->ts_timeleft); }' -p 3247 20 20 20 20 20 20 ????????? 200 ???????????????????? ???????? 200 ??????????????????????????????????????????????????????????????????????????????? DTrace ???????DTrace ??????????????? # dtrace -qn 'sched:::preempt/pid == $target/ { printf("%d\n", ((tsproc_t*)curthread->t_cldata)->ts_cpupri); }' -p 3247 ???????????????????????????? # dtrace -qn 'sched:::preempt/pid == $target/ { printf("%d\n", ((tsproc_t*)curthread->t_cldata)->ts_cpupri); }' -p 3247 0 0 0 0 0 0 ????????????????? 0 ???????? 0 ?????????????????????? dispadmin ???????????????? # dispadmin -c TS -g | head # Time Sharing Dispatcher Configuration RES=1000 # ts_quantum ts_tqexp ts_slpret ts_maxwait ts_lwait PRIORITY LEVEL 200 0 50 0 50 # 0 200 0 50 0 50 # 1 200 0 50 0 50 # 2 200 0 50 0 50 # 3 200 0 50 0 50 # 4 200 0 50 0 50 # 5 ???????PRIORITY LEVEL 0 ???????? ts_quantum ? 200 ??????????? 0 ???? 200 ???????????????????????????(RES ??? 1000 ????ts_quantum ???? 1/1000 ?)? ????????? ????????????????????? mpstat ????????????????????????????icsw ??? 5 ???????????200 ?????????????????????????????????????????????????????? CPU ??? 200 ????????????? # mpstat 1 | egrep '^ 1|csw' CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 347 196 1 42 1 3 0 0 2 9 1 0 90 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 16 0 0 5 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 7 0 0 5 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 8 0 0 5 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 18 1 0 5 0 0 0 0 100 0 0 0 ???????????? Solaris ????????????????????????????????????????????? priocntl ???????????????? 1 ?????????? # priocntl -s -c FX -t 1000 -i pid `pgrep prog01` ??????? mpstat ?????????CPU ??????? 1 ?????????????????????????????????????????????????????????????????????????????????????????????????????????????? # mpstat 1 | egrep '^ 1|csw' CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 346 196 1 42 1 3 0 0 2 9 1 0 90 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 2 0 0 1 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 2 0 0 1 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 13 0 0 2 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 2 0 0 1 0 0 0 0 100 0 0 0 CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 1 0 0 0 5 1 0 1 0 0 0 0 100 0 0 0 ????DTrace ????????????????????????????? # dtrace -qn 'sched:::preempt/pid == $target/ { printf("%d\n", ((fxproc_t*)curthread->t_cldata)->fx_timeleft); }' -p `pgrep prog01` 100 100 100 100 100 100 ??? Solaris ???????????????????????????????????????????????????????????????? 200 ???????????????????????????????????????????????? ??????????????????????????????????????????????????????????????? CPU ?????????I/O ?????????????????????????????????????????????????????????? ?????????????????????????? http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/disp/ ????????? ???????????????????

    Read the article

  • Rle Encoding...What's the wrong?

    - by FILIaS
    I'm trying to make a Rle Encoder Programme.I read the way it works on notes on net. And i tried to fix my code! Regardless I think that the structure and logic of code are right,the code doesnt work! It appears some strange 'Z' as it runs. I really cant find what;s wrong! Could u please give me a piece of advice? Thanx in advance... #include <stdio.h> int main() { int count; unsigned char currChar,prevChar=EOF; while(currChar=getchar() != EOF) { if ( ( (currChar='A')&&(currChar='Z') ) || ( (currChar='a')&&(currChar='z') ) ) { printf("%c",currChar); if(prevChar==currChar) { count=0; currChar=getchar(); while(currChar!='EOF') { if (currChar==prevChar) count++; else { if(count<=9) printf("%d%c",count,prevChar); else { printf("%d%c",reverse(count),prevChar); } prevChar=currChar; break; } } } else prevChar=currChar; if(currChar=='EOF') { printf("%d",count); break; } } else { printf("Error Message:Only characters are accepted! Please try again! False input!"); break; } } return 0; } int reverse(int x) { int piliko,ypoloipo,r=0; x=(x<0)?-x:x; while (x>0) { ypoloipo=x%10; piliko=x/10; r=10*r+ypoloipo; x=piliko; } printf("%d",r); return 0; }

    Read the article

  • Core Audio on iPhone - any way to change the microphone gain (either for speakerphone mic or headpho

    - by Halle
    After much searching the answer seems to be no, but I thought I'd ask here before giving up. For a project I'm working on that includes recording sound, the input levels sound a little quiet both when the route is external mic + speaker and when it's headphone mic + headphones. Does anyone know definitively whether it is possible to programmatically change mic gain levels on the iPhone in any part of Core Audio? If not, is it possible that I'm not really in "speakerphone" mode (with the external mic at least) but only think I am? Here is my audio session init code: OSStatus error = AudioSessionInitialize(NULL, NULL, audioQueueHelperInterruptionListener, r); [...some error checking of the OSStatus...] UInt32 category = kAudioSessionCategory_PlayAndRecord; // need to play out the speaker at full volume too so it is necessary to change default route below error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category); if (error) printf("couldn't set audio category!"); UInt32 doChangeDefaultRoute = 1; error = AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute); if (error) printf("couldn't change default route!"); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); UInt32 inputAvailable = 0; UInt32 size = sizeof(inputAvailable); error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable); if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", (int)error); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); error = AudioSessionSetActive(true); if (error) printf("AudioSessionSetActive (true) failed"); Thanks very much for any pointers.

    Read the article

  • How to convert the date string into string( yyyy-MM-dd). While doing so, I getting null values ?

    - by Madan Mohan
    Hi, I have the data as customerFromDate " 01 Apr 2010 " and customerToDate " 30 Apr 2010 " which is a string. I want to convert that format into yyyy-MM-dd it should be in string. but while doing so. I got null values. Please see the following code which I had tried. printf("\n customerFromDate %s",[customerStatementObj.customerFromDate UTF8String]); printf("\n customerToDate %s",[customerStatementObj.customerToDate UTF8String]); /* prints as the following customerFromDate 01 Apr 2010 customerToDate 30 Apr 2010 */ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *fromDate=[[NSDate alloc]init]; fromDate = [dateFormatter dateFromString:customerStatementObj.customerFromDate]; printf("\n fromDate: %s",[fromDate.description UTF8String]); NSString *fromDateString=[dateFormatter stringFromDate:fromDate]; printf("\n fromDateString: %s",[fromDateString UTF8String]); [dateFormatter release]; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init]; [dateFormatter1 setDateFormat:@"yyyy-MM-dd"]; NSDate *toDate=[[NSDate alloc]init]; toDate = [dateFormatter1 dateFromString:customerStatementObj.customerToDate]; printf("\n toDate: %s",[toDate.description UTF8String]); NSString *toDateString=[dateFormatter1 stringFromDate:toDate]; printf("\n toDateString: %s",[toDateString UTF8String]); [dateFormatter1 release]; Thank you, Madan Mohan.

    Read the article

  • objective-c 2.0 properties and 'retain'

    - by Adam
    Stupid question, but why do we need to use 'retain' when declaring a property? Doesn't it get retained anyway when it's assigned something? Looking at this example, it seems that an object is automatically retained when alloc'ed, so what's the point? #import "Fraction.h" #import <stdio.h> int main( int argc, const char *argv[] ) { Fraction *frac1 = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // increment them [frac1 retain]; // 2 [frac1 retain]; // 3 [frac2 retain]; // 2 // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // decrement [frac1 release]; // 2 [frac2 release]; // 1 // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // release them until they dealloc themselves [frac1 release]; // 1 [frac1 release]; // 0 [frac2 release]; // 0 ¦output Fraction 1 retain count: 1 Fraction 2 retain count: 1 Fraction 1 retain count: 3 Fraction 2 retain count: 2 Fraction 1 retain count: 2 Fraction 2 retain count: 1 Deallocing fraction Deallocing fraction This is driving me crazy!

    Read the article

  • C Programming Logic Error?

    - by mbpluvr64
    The following code compiles fine, but does not allow the user to choose whether or not the program is to run again. After giving the user the answer, the program automatically terminates. I placed the main code in a "do while" loop to have the ability to convert more than one time if I wanted too. I have tried to run the program in the command line (Mac and Ubuntu machines) and within XCode with the exact same results. Any assistance would be greatly appreciated. C Beginner P.S. Compiling on MacBookPro running Snow Leopard. #include <stdio.h> #include <stdlib.h> int main(void) { char anotherIteration = 'Y'; do { const float Centimeter = 2.54f; float inches = 0.0f; float result = 0.0f; // user prompt printf("\nEnter inches: "); scanf("%f", &inches); if (inches < 0) { printf("\nTry again. Enter a positive number.\n"); break; } else { // calculate result result = inches * Centimeter; } printf("%0.2f inches is %0.2f centimeters.\n", inches, result); // flush input fflush(stdin); // user prompt printf("\nWould you like to run the program again? (Y/N): "); scanf("%c", &anotherIteration); if ((anotherIteration != 'Y') || (anotherIteration != 'N')) { printf("\nEnter a Y or a N."); break; } } while(toupper(anotherIteration == 'Y')); printf("Program terminated.\n"); return 0; }

    Read the article

  • confusing fork system call

    - by benjamin button
    Hi, i was just checking the behaviour of fork system call and i found it very confusing. i saw in a website that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces #include <stdio.h> #include <sys/types.h> int main(void) { pid_t pid; char y='Y'; char *ptr; ptr=&y; pid = fork(); if (pid == 0) { y='Z'; printf(" *** Child process ***\n"); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); sleep(5); } else { sleep(5); printf("\n ***parent process ***\n",&y); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); } } the output of the above program is : *** Child process *** Address is 69002894 char value is Z ***parent process *** Address is 69002894 char value is Y so from the above mentioned statement it seems that child and parent have separet address spaces.this is the reason why char value is printed separately and why am i seeing the address of the variable as same in both child and parent processes.? Please help me understand this!

    Read the article

  • Segmentation fault

    - by darkie15
    #include<stdio.h> #include<zlib.h> #include<unistd.h> #include<string.h> int main(int argc, char *argv[]) { char *path=NULL; size_t size; int index ; printf("\nArgument count is = %d", argc); printf ("\nThe 0th argument to the file is %s", argv[0]); path = getcwd(path, size); printf("\nThe current working directory is = %s", path); if (argc <= 1) { printf("\nUsage: ./output filename1 filename2 ..."); } else if (argc > 1) { for (index = 1; index <= argc;index++) { printf("\n File name entered is = %s", argv[index]); strcat(path,argv[index]); printf("\n The complete path of the file name is = %s", path); } } return 0; } In the above code, here is the output that I get while running the code: $ ./output test.txt Argument count is = 2 The 0th argument to the file is ./output The current working directory is = /home/welcomeuser File name entered is = test.txt The complete path of the file name is = /home/welcomeusertest.txt Segmentation fault (core dumped) Can anyone please me understand why I am getting a core dumped error? Regards, darkie

    Read the article

  • What happens when we combine RAII and GOTO ?

    - by Robert Gould
    I'm wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of Goto (lovely idea isn't it). class Two { public: ~Two() { printf("2,"); } }; class Ghost { public: ~Ghost() { printf(" BOO! "); } }; void foo() { { Two t; printf("1,"); goto JUMP; } Ghost g; JUMP: printf("3"); } int main() { foo(); } When running the following code in VS2005 I get the following output: 1,2,3 BOO! However I imagined, guessed, hoped that 'BOO!' wouldn't actually appear as the Ghost should have never been instantiated (IMHO, because I don't know the actual expected behavior of this code). Any Guru out there knows what's up? Just realized that if I instantiate an explicit constructor for Ghost the code doesn't compile... class Ghost { public: Ghost() { printf(" HAHAHA! "); } ~Ghost() { printf(" BOO! "); } }; Ah, the mystery ...

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >