Search Results

Search found 9 results on 1 pages for 'atol'.

Page 1/1 | 1 

  • atol(), atof(), atoi() function behaviours, is there a stable way to convert from/to string/integer

    - by Berkay
    In these days i'm playing with the C functions of atol(), atof() and atoi(), from a blog post i find a tutorial and applied: here are my results: void main() char a[10],b[10]; puts("Enter the value of a"); gets(a); puts("Enter the value of b"); gets(b); printf("%s+%s=%ld and %s-%s=%ld",a,b,(atol(a)+atol(b)),a,b,(atol(a)-atol(b))); getch(); } there is atof() which returns the float value of the string and atoi() which returns integer value. now to see the difference between the 3 i checked this code: main() { char a[]={"2545.965"}; printf("atol=%ld\t atof=%f\t atoi=%d\t\n",atol(a),atof(a),atoi(a)); } the output will be atol=2545 atof=2545.965000 atoi=2545 char a[]={“heyyou”}; now when you run the program the following will be the output (why?, is there any solution to convert pure strings to integer?) atol=0 atof=0 atoi=0 the string should contain numeric value now modify this program as char a[]={“007hey”}; the output in this case(tested in Red hat) will be atol=7 atof=7.000000 atoi=7 so the functions has taken 007 only not the remaining part (why?) Now consider this char a[]={“hey007?}; the output of the program will be atol=0 atof=0.000000 atoi=0 So i just want to convert my strings to number and then again to same text, i played with these functions and as you see i'm getting really interesting results? why is that? any other functions to convert from/to string/integer and vice versa?

    Read the article

  • Scala unsatisfiable cyclic dependency in "table-layout" library (Toolkit class)

    - by Atol
    When I try to compile with sbt some code containing an instance of a Table from this library I get this error: java.lang.AssertionError: assertion failed: unsatisfiable cyclic dependency in 'class Toolkit' It seems to work with Java so I don't understand why it fails in Scala. Here is the toolkit class: http://code.google.com/p/table-layout/source/browse/branches/v1/tablelayout/src/com/esotericsoftware/tablelayout/Toolkit.java As long as I get this error I'm totally stopped in my project :(.

    Read the article

  • Serious Memory Clash: Variables clashing in C

    - by Soham
    int main(int argc, char*argv[]) { Message* newMessage; Asset* Check; //manipulation and initialization of Check, so that it holds proper values. newMessage = parser("N,2376,01/02/2011 09:15:01.342,JPASSOCIAT FUTSTK 24FEB2011,B,84.05,2000,0,0",newMessage); // MessageProcess(newMessage,AssetMap); printf("LAST TRADE ADDRESS %p LAST TRADE TIME %s\n",Check->TradeBook,Check->Time); } Message* parser(char *message,Message* new_Message) { char a[9][256]; char* tmp =message; bool inQuote=0; int counter=0; int counter2=0; new_Message = (Message*)malloc(sizeof(Message)); while(*tmp!='\0') { switch(*tmp) { case ',': if(!inQuote) { a[counter][counter2]='\0'; counter++; counter2=0; } break; case '"': inQuote=!inQuote; break; default: a[counter][counter2]=*tmp; counter2++; break; } tmp++; } a[counter][counter2]='\0'; new_Message->type = *a[0]; new_Message->Time = &a[2][11]; new_Message->asset = a[3]; if(*a[4]=='S') new_Message->BS = 0; else new_Message->BS = 1; new_Message->price1=atof(a[5]); new_Message->shares1=atol(a[6]); new_Message->price2=atof(a[7]); new_Message->shares2=atol(a[8]); new_Message->idNum = atoi(a[1]); return(new_Message); } Here there is a serious memory clash, in two variables of different scope. I have investigated using gdb and it seems the address of new_Message->Time is equalling to the address of Check->Time. They both are structures of different types I am trying to resolve this issue, because, when parser changes the value of new_Message->Time it manipulates the contents of Check-Time Please do suggest how to solve this problem. I have lost(spent) around 10 hours and counting to resolve this issue, and tons of hair. Soham

    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

  • Segmentation fault on the server, but not local machine

    - by menachem-almog
    As stated in the title, the program is working on my local machine (ubuntu 9.10) but not on the server (linux). It's a grid hosting hosting package of godaddy. Please help.. Here is the code: #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { long offset; FILE *io; unsigned char found; unsigned long loc; if (argc != 2) { printf("syntax: find 0000000\n"); return 255; } offset = atol(argv[1]) * (sizeof(unsigned char)+sizeof(unsigned long)); io = fopen("index.dat","rb"); fseek(io,offset,SEEK_SET); fread(&found,sizeof(unsigned char),1,io); fread(&loc,sizeof(unsigned long),1,io); if (found == 1) printf("%d\n",loc); else printf("-1\n"); fclose(io); return 0; } EDIT: It's not my program. I wish I knew enough C in order to fix it, but I'm on a deadline. This program is meant to find the first occurrence of a 7 digit number in the PI sequence, index.dat contains an huge array number = position. http://jclement.ca/fun/pi/search.cgi

    Read the article

  • Segmentation Fault (C) occur on the server, but works on local machine

    - by menachem-almog
    As stated in the title, the program is working on my local machine (ubuntu 9.10) but not on the server (linux). It's a grid hosting hosting package of godaddy. Please help.. Here is the code: #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { long offset; FILE *io; unsigned char found; unsigned long loc; if (argc != 2) { printf("syntax: find 0000000\n"); return 255; } offset = atol(argv[1]) * (sizeof(unsigned char)+sizeof(unsigned long)); io = fopen("index.dat","rb"); fseek(io,offset,SEEK_SET); fread(&found,sizeof(unsigned char),1,io); fread(&loc,sizeof(unsigned long),1,io); if (found == 1) printf("%d\n",loc); else printf("-1\n"); fclose(io); return 0; }

    Read the article

  • LLVM JIT segfaults. What am I doing wrong?

    - by bugspy.net
    It is probably something basic because I am just starting to learn LLVM.. The following creates a factorial function and tries to git and execute it (I know the generated func is correct because I was able to static compile and execute it). But I get segmentation fault upon execution of the function (in EE-runFunction(TheF, Args)) #include <iostream> #include "llvm/Module.h" #include "llvm/Function.h" #include "llvm/PassManager.h" #include "llvm/CallingConv.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/IRBuilder.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/GenericValue.h" using namespace llvm; Module* makeLLVMModule() { // Module Construction LLVMContext& ctx = getGlobalContext(); Module* mod = new Module("test", ctx); Constant* c = mod->getOrInsertFunction("fact64", /*ret type*/ IntegerType::get(ctx,64), IntegerType::get(ctx,64), /*varargs terminated with null*/ NULL); Function* fact64 = cast<Function>(c); fact64->setCallingConv(CallingConv::C); /* Arg names */ Function::arg_iterator args = fact64->arg_begin(); Value* x = args++; x->setName("x"); /* Body */ BasicBlock* block = BasicBlock::Create(ctx, "entry", fact64); BasicBlock* xLessThan2Block= BasicBlock::Create(ctx, "xlst2_block", fact64); BasicBlock* elseBlock = BasicBlock::Create(ctx, "else_block", fact64); IRBuilder<> builder(block); Value *One = ConstantInt::get(Type::getInt64Ty(ctx), 1); Value *Two = ConstantInt::get(Type::getInt64Ty(ctx), 2); Value* xLessThan2 = builder.CreateICmpULT(x, Two, "tmp"); //builder.CreateCondBr(xLessThan2, xLessThan2Block, cond_false_2); builder.CreateCondBr(xLessThan2, xLessThan2Block, elseBlock); /* Recursion */ builder.SetInsertPoint(elseBlock); Value* xMinus1 = builder.CreateSub(x, One, "tmp"); std::vector<Value*> args1; args1.push_back(xMinus1); Value* recur_1 = builder.CreateCall(fact64, args1.begin(), args1.end(), "tmp"); Value* retVal = builder.CreateBinOp(Instruction::Mul, x, recur_1, "tmp"); builder.CreateRet(retVal); /* x<2 */ builder.SetInsertPoint(xLessThan2Block); builder.CreateRet(One); return mod; } int main(int argc, char**argv) { long long x; if(argc > 1) x = atol(argv[1]); else x = 4; Module* Mod = makeLLVMModule(); verifyModule(*Mod, PrintMessageAction); PassManager PM; PM.add(createPrintModulePass(&outs())); PM.run(*Mod); // Now we going to create JIT ExecutionEngine *EE = EngineBuilder(Mod).create(); // Call the function with argument x: std::vector<GenericValue> Args(1); Args[0].IntVal = APInt(64, x); Function* TheF = cast<Function>(Mod->getFunction("fact64")) ; /* The following CRASHES.. */ GenericValue GV = EE->runFunction(TheF, Args); outs() << "Result: " << GV.IntVal << "\n"; delete Mod; return 0; }

    Read the article

  • Streamed mp3 only plays for 1 second

    - by angel6
    Hi, I'm using the plaympeg.c (modified) code of smpeg as a media player. I've got ffserver running as a streaming server. I'm a streaming an mp3 file over http. But when I run plaympeg.c, it plays the streamed file only for a second. When I run plaympeg again, it starts off from where it left and plays for 1 second. Does anyone know why this happens an how to fix it? I've tested it out on WMP and it plays the entire file in one go. So, i guess it's not a problem with the streaming or ffserver.conf include include include include /* #ifdef unix */ include include include include include include include define NET_SUPPORT /* General network support */ define HTTP_SUPPORT /* HTTP support */ ifdef NET_SUPPORT include include include include endif include "smpeg.h" ifdef NET_SUPPORT int tcp_open(char * address, int port) { struct sockaddr_in stAddr; struct hostent * host; int sock; struct linger l; memset(&stAddr,0,sizeof(stAddr)); stAddr.sin_family = AF_INET ; stAddr.sin_port = htons(port); if((host = gethostbyname(address)) == NULL) return(0); stAddr.sin_addr = *((struct in_addr *) host-h_addr_list[0]) ; if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) return(0); l.l_onoff = 1; l.l_linger = 5; if(setsockopt(sock, SOL_SOCKET, SO_LINGER, (char*) &l, sizeof(l)) < 0) return(0); if(connect(sock, (struct sockaddr *) &stAddr, sizeof(stAddr)) < 0) return(0); return(sock); } ifdef HTTP_SUPPORT int http_open(char * arg) { char * host; int port; char * request; int tcp_sock; char http_request[1024]; char c; printf("\nin http_open passed parameter = %s\n",arg); /* Check for URL syntax */ if(strncmp(arg, "http://", strlen("http://"))) return(0); /* Parse URL */ port = 80; host = arg + strlen("http://"); if((request = strchr(host, '/')) == NULL) return(0); request++ = 0; if(strchr(host, ':') != NULL) / port is specified */ { port = atoi(strchr(host, ':') + 1); *strchr(host, ':') = 0; } /* Open a TCP socket */ if(!(tcp_sock = tcp_open(host, port))) { perror("http_open"); return(0); } /* Send HTTP GET request */ sprintf(http_request, "GET /%s HTTP/1.0\r\n" "User-Agent: Mozilla/2.0 (Win95; I)\r\n" "Pragma: no-cache\r\n" "Host: %s\r\n" "Accept: /\r\n" "\r\n", request, host); send(tcp_sock, http_request, strlen(http_request), 0); /* Parse server reply */ do read(tcp_sock, &c, sizeof(char)); while(c != ' '); read(tcp_sock, http_request, 4*sizeof(char)); http_request[4] = 0; if(strcmp(http_request, "200 ")) { fprintf(stderr, "http_open: "); do { read(tcp_sock, &c, sizeof(char)); fprintf(stderr, "%c", c); } while(c != '\r'); fprintf(stderr, "\n"); return(0); } return(tcp_sock); } endif endif void update(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h) { if ( screen-flags & SDL_DOUBLEBUF ) { SDL_Flip(screen); } } /* Flag telling the UI that the movie or song should be skipped */ int done; void next_movie(int sig) { done = 1; } int main(int argc, char *argv[]) { int use_audio, use_video; int fullscreen; int scalesize; int scale_width, scale_height; int loop_play; int i, pause; int volume; Uint32 seek; float skip; int bilinear_filtering; SDL_Surface *screen; SMPEG *mpeg; SMPEG_Info info; char *basefile; SDL_version sdlver; SMPEG_version smpegver; int fd; char buf[32]; int status; printf("\nchecking command line options "); /* Get the command line options */ use_audio = 1; use_video = 1; fullscreen = 0; scalesize = 1; scale_width = 0; scale_height = 0; loop_play = 0; volume = 100; seek = 0; skip = 0; bilinear_filtering = 0; fd = 0; for ( i=1; argv[i] && (argv[i][0] == '-') && (argv[i][1] != 0); ++i ) { if ( strcmp(argv[i], "--fullscreen") == 0 ) { fullscreen = 1; } else if ((strcmp(argv[i], "--seek") == 0)||(strcmp(argv[i], "-S") == 0)) { ++i; if ( argv[i] ) { seek = atol(argv[i]); } } else if ((strcmp(argv[i], "--volume") == 0)||(strcmp(argv[i], "-v") == 0)) { ++i; if (i >= argc) { fprintf(stderr, "Please specify volume when using --volume or -v\n"); return(1); } if ( argv[i] ) { volume = atoi(argv[i]); } if ( ( volume < 0 ) || ( volume 100 ) ) { fprintf(stderr, "Volume must be between 0 and 100\n"); volume = 100; } } else { fprintf(stderr, "Warning: Unknown option: %s\n", argv[i]); } } printf("\nuse video = %d, use audio = %d\n",use_video, use_audio); printf("\ngoing to check input parameters\n"); if defined(linux) || defined(FreeBSD) /* Plaympeg doesn't need a mouse */ putenv("SDL_NOMOUSE=1"); endif /* Play the mpeg files! */ status = 0; for ( ; argv[i]; ++i ) { /* Initialize SDL */ if ( use_video ) { if ((SDL_Init(SDL_INIT_VIDEO) < 0) || !SDL_VideoDriverName(buf, 1)) { fprintf(stderr, "Warning: Couldn't init SDL video: %s\n", SDL_GetError()); fprintf(stderr, "Will ignore video stream\n"); use_video = 0; } printf("\ninitialised video\n"); } if ( use_audio ) { if ((SDL_Init(SDL_INIT_AUDIO) < 0) || !SDL_AudioDriverName(buf, 1)) { fprintf(stderr, "Warning: Couldn't init SDL audio: %s\n", SDL_GetError()); fprintf(stderr, "Will ignore audio stream\n"); use_audio = 0; } } /* Allow Ctrl-C when there's no video output */ signal(SIGINT, next_movie); printf("\nchecking defined supports\n"); /* Create the MPEG stream */ ifdef NET_SUPPORT printf("\ndefined NET_SUPPORT\n"); ifdef HTTP_SUPPORT printf("\ndefined HTTP_SUPPORT\n"); /* Check if source is an http URL */ printf("\nabout to call http_open\n"); printf("\nhere we go\n"); if((fd = http_open(argv[i])) != 0) mpeg = SMPEG_new_descr(fd, &info, use_audio); else endif endif { if(strcmp(argv[i], "-") == 0) /* Use stdin for input */ mpeg = SMPEG_new_descr(0, &info, use_audio); else mpeg = SMPEG_new(argv[i], &info, use_audio); } if ( SMPEG_error(mpeg) ) { fprintf(stderr, "%s: %s\n", argv[i], SMPEG_error(mpeg)); SMPEG_delete(mpeg); status = -1; continue; } SMPEG_enableaudio(mpeg, use_audio); SMPEG_enablevideo(mpeg, use_video); SMPEG_setvolume(mpeg, volume); /* Print information about the video */ basefile = strrchr(argv[i], '/'); if ( basefile ) { ++basefile; } else { basefile = argv[i]; } if ( info.has_audio && info.has_video ) { printf("%s: MPEG system stream (audio/video)\n", basefile); } else if ( info.has_audio ) { printf("%s: MPEG audio stream\n", basefile); } else if ( info.has_video ) { printf("%s: MPEG video stream\n", basefile); } if ( info.has_video ) { printf("\tVideo %dx%d resolution\n", info.width, info.height); } if ( info.has_audio ) { printf("\tAudio %s\n", info.audio_string); } if ( info.total_size ) { printf("\tSize: %d\n", info.total_size); } if ( info.total_time ) { printf("\tTotal time: %f\n", info.total_time); } /* Set up video display if needed */ if ( info.has_video && use_video ) { const SDL_VideoInfo *video_info; Uint32 video_flags; int video_bpp; int width, height; /* Get the "native" video mode */ video_info = SDL_GetVideoInfo(); switch (video_info->vfmt->BitsPerPixel) { case 16: case 24: case 32: video_bpp = video_info->vfmt->BitsPerPixel; break; default: video_bpp = 16; break; } if ( scale_width ) { width = scale_width; } else { width = info.width; } width *= scalesize; if ( scale_height ) { height = scale_height; } else { height = info.height; } height *= scalesize; video_flags = SDL_SWSURFACE; if ( fullscreen ) { video_flags = SDL_FULLSCREEN|SDL_DOUBLEBUF|SDL_HWSURFACE; } video_flags |= SDL_ASYNCBLIT; video_flags |= SDL_RESIZABLE; screen = SDL_SetVideoMode(width, height, video_bpp, video_flags); if ( screen == NULL ) { fprintf(stderr, "Unable to set %dx%d video mode: %s\n", width, height, SDL_GetError()); continue; } SDL_WM_SetCaption(argv[i], "plaympeg"); if ( screen->flags & SDL_FULLSCREEN ) { SDL_ShowCursor(0); } SMPEG_setdisplay(mpeg, screen, NULL, update); SMPEG_scaleXY(mpeg, screen->w, screen->h); } else { SDL_QuitSubSystem(SDL_INIT_VIDEO); } /* Set any special playback parameters */ if ( loop_play ) { SMPEG_loop(mpeg, 1); } /* Seek starting position */ if(seek) SMPEG_seek(mpeg, seek); /* Skip seconds to starting position */ if(skip) SMPEG_skip(mpeg, skip); /* Play it, and wait for playback to complete */ SMPEG_play(mpeg); done = 0; pause = 0; while ( ! done && ( pause || (SMPEG_status(mpeg) == SMPEG_PLAYING) ) ) { SDL_Event event; while ( use_video && SDL_PollEvent(&event) ) { switch (event.type) { case SDL_VIDEORESIZE: { SDL_Surface *old_screen = screen; SMPEG_pause(mpeg); screen = SDL_SetVideoMode(event.resize.w, event.resize.h, screen->format->BitsPerPixel, screen->flags); if ( old_screen != screen ) { SMPEG_setdisplay(mpeg, screen, NULL, update); } SMPEG_scaleXY(mpeg, screen-w, screen-h); SMPEG_pause(mpeg); } break; case SDL_KEYDOWN: if ( (event.key.keysym.sym == SDLK_ESCAPE) || (event.key.keysym.sym == SDLK_q) ) { // Quit done = 1; } else if ( event.key.keysym.sym == SDLK_RETURN ) { // toggle fullscreen if ( event.key.keysym.mod & KMOD_ALT ) { SDL_WM_ToggleFullScreen(screen); fullscreen = (screen-flags & SDL_FULLSCREEN); SDL_ShowCursor(!fullscreen); } } else if ( event.key.keysym.sym == SDLK_UP ) { // Volume up if ( volume < 100 ) { if ( event.key.keysym.mod & KMOD_SHIFT ) { // 10+ volume += 10; } else if ( event.key.keysym.mod & KMOD_CTRL ) { // 100+ volume = 100; } else { // 1+ volume++; } if ( volume 100 ) volume = 100; SMPEG_setvolume(mpeg, volume); } } else if ( event.key.keysym.sym == SDLK_DOWN ) { // Volume down if ( volume 0 ) { if ( event.key.keysym.mod & KMOD_SHIFT ) { volume -= 10; } else if ( event.key.keysym.mod & KMOD_CTRL ) { volume = 0; } else { volume--; } if ( volume < 0 ) volume = 0; SMPEG_setvolume(mpeg, volume); } } else if ( event.key.keysym.sym == SDLK_PAGEUP ) { // Full volume volume = 100; SMPEG_setvolume(mpeg, volume); } else if ( event.key.keysym.sym == SDLK_PAGEDOWN ) { // Volume off volume = 0; SMPEG_setvolume(mpeg, volume); } else if ( event.key.keysym.sym == SDLK_SPACE ) { // Toggle play / pause if ( SMPEG_status(mpeg) == SMPEG_PLAYING ) { SMPEG_pause(mpeg); pause = 1; } else { SMPEG_play(mpeg); pause = 0; } } else if ( event.key.keysym.sym == SDLK_RIGHT ) { // Forward if ( event.key.keysym.mod & KMOD_SHIFT ) { SMPEG_skip(mpeg, 100); } else if ( event.key.keysym.mod & KMOD_CTRL ) { SMPEG_skip(mpeg, 50); } else { SMPEG_skip(mpeg, 5); } } else if ( event.key.keysym.sym == SDLK_LEFT ) { // Reverse if ( event.key.keysym.mod & KMOD_SHIFT ) { } else if ( event.key.keysym.mod & KMOD_CTRL ) { } else { } } else if ( event.key.keysym.sym == SDLK_KP_MINUS ) { // Scale minus if ( scalesize > 1 ) { scalesize--; } } else if ( event.key.keysym.sym == SDLK_KP_PLUS ) { // Scale plus scalesize++; } else if ( event.key.keysym.sym == SDLK_f ) { // Toggle filtering on/off if ( bilinear_filtering ) { SMPEG_Filter *filter = SMPEGfilter_null(); filter = SMPEG_filter( mpeg, filter ); filter-destroy(filter); bilinear_filtering = 0; } else { SMPEG_Filter *filter = SMPEGfilter_bilinear(); filter = SMPEG_filter( mpeg, filter ); filter-destroy(filter); bilinear_filtering = 1; } } break; case SDL_QUIT: done = 1; break; default: break; } } SDL_Delay(1000/2); } SMPEG_delete(mpeg); } SDL_Quit(); if defined(HTTP_SUPPORT) if(fd) close(fd); endif return(status); }

    Read the article

1