/* * Read a line of data from the NNTP socket. If something gives, do reconnect * * Parameters: "string" has the buffer space for the line received. * "size" is maximum size of the buffer to read. * * Returns: NULL on end of stream, or a line of data. * Basically, we try to act like fgets() on an NNTP stream. * * Side effects: Talks to server, changes contents of "string". * Reopens connection when necessary and requested. * Exits via tin_done() if fatal error occurs. */ char * get_server( char *string, int size) { int retry = NNTP_TRY_RECONNECT; reconnected_in_last_get_server = FALSE; errno = 0; /* * NULL socket reads indicates socket has closed. Try a few times more */ while (nntp_rd_fp == NULL || s_gets(string, size, nntp_rd_fp) == NULL) { if (quitting) /* Don't bother to reconnect */ tin_done(NNTP_ERROR_EXIT); /* And don't try to disconnect again! */ # ifdef DEBUG if (errno != 0 && errno != EINTR) /* Will only confuse end users */ perror_message("get_server()"); # endif /* DEBUG */ /* * Reconnect only if command was not "QUIT" anyway (in which case a * reconnection would be useless because the connection will be * closed immediately). Also prevents tin from asking to reconnect * when user is quitting tin if tinrc.auto_reconnect is false. */ if (strncmp(last_put, "QUIT", 4)) { retry = reconnect(retry); /* Will abort when out of tries */ reconnected_in_last_get_server = TRUE; } else { /* * Use standard NNTP closing message and response code if user is * quitting tin and leave loop. */ strncpy(string, _(txt_nntp_ok_goodbye), size - 2); strcat(string, cCRLF); /* tin_fgets() needs CRLF */ break; } } return string; }
int main(void) { char choice[LEN]; enum spectrum color; bool color_is_found = false; puts("\n"); puts("Enter a color (empty line to quit):"); while (s_gets(choice, LEN) != NULL && choice[0] != '\0') { for (color = red; color <= violet; color++) { if (strcmp(choice, colors[color]) == 0) { color_is_found = true; break; } } puts(""); if (color_is_found) switch(color) { case red : puts("Roses are red."); break; case orange : puts("Poppies are orange."); break; case yellow : puts("Sunflowers are yellow."); break; case green : puts("Grass is green."); break; case blue : puts("Bluebells are blue."); break; case violet : puts("Violets are violet."); break; } else printf("I don't know about the color %s.\n", choice); color_is_found = false; puts("\nNext color, please (empty line to quit):"); } puts("Goodbye!"); puts("\n"); return 0; }
int main(void) { char flower[SIZE]; char addon[] = "s smell like old shoes."; puts("What is your favorite flower?"); if (s_gets(flower, SIZE)) { strcat(flower, addon); puts(flower); puts(addon); } else puts("End of file encountered!"); puts("bye"); return 0; }
int main() { char number[LIM]; char * end; long value; puts("Enter a number (empty line to quit):"); while(s_gets(number, LIM) && number[0] != '\0') { value = strtol(number, &end, 10); /* base 10 */ printf("base 10 input, base 10 output: %ld, stopped at %s (%d)\n", value, end, *end); value = strtol(number, &end, 16); /* base 16 */ printf("base 16 input, base 10 output: %ld, stopped at %s (%d)\n", value, end, *end); puts("Next number:"); } puts("Bye!\n"); return 0; }
int main(void) { char month_name[NAMELEN]; int days; puts("Enter the name of the month, end with an empty line:"); while (s_gets(month_name, NAMELEN) != NULL && month_name[0] != '\0') { days = daysupto(month_name); if (days) { printf("Total days in the year up to and including "); printf("%s is %d\n", month_name, days); } else printf("Your name of month is incorrect!\n"); puts("Enter the next name of the month:"); } puts("Done!"); return 0; }
int main(void) { char input[LIM][SIZE]; char * ptstr[LIM]; int ct = 0; int k; printf("Input up to %d lines, and I will sort them.\n", LIM); printf("To stop, press the Enter key at a line's start.\n"); while (ct < LIM && s_gets(input[ct], SIZE) != NULL && input[ct][0] != '\0') { ptstr[ct] = input[ct]; ct++; } stsrt(ptstr, ct); puts("\nHere's the sorted list:\n"); for (k = 0; k < ct; k++) puts(ptstr[k]); return 0; }
int main(void) { char qwords[LIM][SIZE]; char temp[SIZE]; int i = 0; printf("Enter %d words beginning with q:\n", LIM); while (i < LIM && s_gets(temp, SIZE)) { if (temp[0] != 'q') printf("%s doesn't begin with q!\n", temp); else { strcpy(qwords[i], temp); i++; } } puts("Here are the words accepted:"); for (i = 0; i < LIM; i++) puts(qwords[i]); return 0; }
int main(void) { char numstring[20]; int n; int oknum; int numint; int pow; int numdigits; char digchar; int digit; int neg; int num; setlocale(LC_NUMERIC, ""); puts("\n"); printf("INT_MAX = %'d\n", INT_MAX); // printf("INT_MAX + 1 = %'d\n", (INT_MAX + 1)); printf("INT_MIN= %'d\n", INT_MIN); // printf("INT_MIN - 1 = %'d\n", (INT_MIN - 1)); // printf("Environment Variable LC_NUMERIC = %s\n", getenv("LC_NUMERIC")); // num = atoi("2147483647"); // printf("num = %'d\n", num); // num = 0; // num += (int)('1'); // printf("num = %'d\n", num); printf("Enter an integer . . . "); s_gets(numstring, 20); n = 0; oknum = 1; numint = 0; pow = 1; numdigits = 0; neg = 0; while (numstring[n] != '\0' && oknum) { numdigits++; digchar = numstring[n]; if ((digchar == '-') && (n == 0)) { neg = 1; n++; continue; } if ((digchar < 48) || (digchar > 57)) { oknum = 0; printf("The number you entered wasn't an integer"); printf(" or contained non-numeric characters.\n"); continue; } if (numdigits > (10 + neg)) { oknum = 0; printf("The number you entered is too large to be stored "); printf("as an integer in this system.\n"); continue; } n++; } if (oknum) { for (n = (numdigits - 1); n >= neg; n--) { digchar = numstring[n]; digit = ((int)digchar) - 48; if (((n - neg) == 0) && (digit >= 2) && ((numint > 147483647) || (numint < -147483648))) { printf("The number you entered is too large to be stored "); printf("as an integer in this system.\n"); oknum = 0; break; } if (neg) numint -= (pow * digit); else numint += (pow * digit); pow *= 10; } } if (oknum) { printf("numstring: "); for (n = 0; n < numdigits; n++) { printf("%c", numstring[n]); if ((n >= neg) && (((n + 1) % 3) == (numdigits % 3)) && (n < (numdigits - neg - 1))) printf(","); } printf("\n"); printf("numint: %'d\n", numint); } puts("\n"); return 0; }
void CFtpDialog::ListDirectory() { if (fSocket < 0) { beep(); return; } for (int i = fListView->CountItems() - 1; i >= 0; i--) delete fListView->RemoveItem(i); int data = 0; try { struct sockaddr_in saData; struct sockaddr_in saCmd; data = socket(AF_INET, SOCK_STREAM, 0); if (data < 0) THROW(("Failed to get socket: %s", strerror(errno))); memset(&saData, 0, sizeof(saData)); saData.sin_family = AF_INET; socklen_t size = sizeof(saData); bool passive = IsOn("pssv"); if (passive) { // switch to passive mode s_printf(fSocketFD, "pasv\r\n"); } else { FailSockErr(bind(data, (struct sockaddr *)&saData, sizeof(saData))); FailSockErr(listen(data, 5)); // [zooey]: calling getsockname() on a socket that has been bound to // IN_ADDR_ANY (the wildcard-address) will *not* return any IP-address, // as this will only be setup by the system during connect or accept. // [refer to W.R. Stevens - Unix Network Programming, Vol 1, p. 92] // BeOS R5 however, *does* fill in the IP-address at this stage (that's // why this code worked for R5 but didn't work for BONE). // In order to fix this problem, we simply use the IP-address of the // command-socket for the PORT-command: // // fetch port from data-socket: FailSockErr(getsockname(data, (struct sockaddr *)&saData, &size)); unsigned char *pap = (unsigned char *)&saData.sin_port; // fetch ip-address from cmd-socket: FailSockErr(getsockname(fSocketFD->sSocket, (struct sockaddr *)&saCmd, &size)); unsigned char *sap = (unsigned char *)&saCmd.sin_addr.s_addr; // combine both into the PORT-command: s_printf(fSocketFD, "port %d,%d,%d,%d,%d,%d\r\n", sap[0], sap[1], sap[2], sap[3], pap[0], pap[1]); } int state = 1; SOCK* dsf = NULL; while (state) { GetReply(); switch (state) { case 1: if (passive) { unsigned int sap[4]; unsigned int pap[2]; if (*fReply != '2') THROW(("Pasv command failed: %s", fReply)); char* pos = strchr(fReply,'('); if (!pos) THROW(("Answer to Pasv has unknown format: %s", fReply)); int cnt = sscanf(pos+1, "%u,%u,%u,%u,%u,%u", &sap[0], &sap[1], &sap[2], &sap[3], &pap[0], &pap[1]); if (cnt != 6) THROW(("Could not parse answer to Pasv (%d of 6): %s", cnt, fReply)); char ipAddr[20]; sprintf(ipAddr, "%d.%d.%d.%d", sap[0], sap[1], sap[2], sap[3]); saData.sin_port = htons(pap[0]*256+pap[1]); saData.sin_addr.s_addr = inet_addr(ipAddr); FailOSErr(connect(data, (struct sockaddr *)&saData, sizeof(saData))); dsf = s_open(data, "r+"); } else { if (*fReply != '2') THROW(("Port command failed: %s", fReply)); } s_printf(fSocketFD, "list\r\n"); state = 2; break; case 2: if (*fReply == '1') { int ds = 0; if (!passive) { FailSockErr(ds = accept(data, (struct sockaddr *)&saData, &size)); dsf = s_open(ds, "r+"); } try { CFtpListItem *item; char s[256]; bool showAll = IsOn("dotf"); int entryCount = 0; while (s_gets(s, 256, dsf)) { entryCount++; item = new CFtpListItem(this, s); if (item->IsValid() && (showAll || !item->IsDotFile())) { fListView->AddItem(item); } else delete item; } if (entryCount == 0) THROW(("Could not get listing.")); fListView->Invalidate(); UpdateIfNeeded(); s_close(dsf); if (!passive) closesocket(ds); } catch (HErr& e) { EnableUpdates(); s_close(dsf); closesocket(ds); throw; } state = 3; } else THROW(("Failed to get listing: %s", fReply)); break; case 3: if (*fReply != '2') THROW(("Something went wrong fetching the directory listing")); state = 0; break; } } closesocket(data); } catch (HErr& e) { if (data) closesocket(data); e.DoError(); } } // CFtpDialog::ListDirectory
int main(int argc, char* argv[]) { char* vip = NULL; //IP-Adresse des Servers, Variable muss später freigegeben werden int vport = -1; //Portnummer // int error = 0; //nur temorär verwendet zum debugging memset(username,'\0',sizeof(username)); /* Start der GETOPT behandlung */ { int c; int counter = 0; int sl = 0; if(argc <3) print_usage(); while( (c = getopt(argc, argv, "i:p:")) != EOF ) { switch (c) { case 'p': if(vport!=-1) { print_usage(); break; } vport = strtol(optarg,(char**)NULL,10); counter++; break; case 'i': if(vip!=NULL) { print_usage(); break; } sl = strlen(optarg); vip = (char*) malloc(sizeof(char)* (sl+1)); strcpy(vip, optarg); counter++; break; case '?': print_usage(); break; } } // printf("\nIP: %s, Port: %d\n",vip, vport); // printf("\nCounter: %d; optind: %d; argc: %d\n", counter, optind, argc); if(counter!= 2 || optind!=argc || vport < 1) print_usage(); //printf("\n FERTIG\n "); /* ENDE GETOPT */ } /* Kommunikation mit server */ { int create_socket; char buffer[BUF]; struct sockaddr_in address; char* command; char* file; memset(buffer,'\0',sizeof(buffer)); /* Socket erstellen */ { if ((create_socket = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket error"); return EXIT_FAILURE; } memset(&address,0,sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons (vport); inet_aton(vip, &address.sin_addr); free(vip); } /* connect */ { if (connect ( create_socket, (struct sockaddr *) &address, sizeof (address)) == 0) { clrscr(); do { if(read(create_socket,buffer,BUF)==-1) perror("Error reading stuff"); if(!strcmp(buffer,"fail")) { perror("Server failed, shutting down client..."); close (create_socket); return EXIT_FAILURE; } if(!strncasecmp(buffer,"block",5)) { strtok(buffer, "|"); char* printmsg = strtok(NULL, "|"); printf("\n%s\nShutting down client..\n",printmsg); close(create_socket); return EXIT_FAILURE; } } while(strcmp(buffer,"win")); printf ("Connection with server (%s) established\nPlease log in first with comand: \"LOGIN\"\n", inet_ntoa (address.sin_addr)); } else { perror("Connect error - no server available"); return EXIT_FAILURE; } } do { login = 0; printf ("Send command: "); s_gets(buffer, BUF); /* String trennen */ { char buf2[BUF]; strcpy(buf2,buffer); command = strtok(buf2, " "); file = strtok(NULL, "\n"); // printf("Command: %s\nFile: %s\nbuf2: %s\n\n",command,file,buf2); } // printf("Command = %s\n", command); // if(file!=NULL) //printf("File = %s\n", file); /* Befehl ausführen */ { if(!strcasecmp(command, "LIST")) { if(send(create_socket, command, strlen (command), 0)==-1) perror("Error sending stuff"); do { if(read(create_socket,buffer,BUF)==-1) perror("Error reading stuff"); if(!strcmp(buffer,"log")) { // printf("Server refused, login first\n"); login=1; break; } } while(strcmp(buffer,"server ready")); if(!login) { printf("List wird ausgeführt\n\nListe:\n"); memset(buffer,'\0',sizeof(buffer)); { strcpy(buffer,"start"); if(write(create_socket,buffer,BUF)==-1) perror("Error writing stuff"); memset(buffer,'\0',sizeof(buffer)); } do { if(read(create_socket,buffer, BUF)==-1) perror("Error writing stuff"); //buffer[BUF-1] = '\0'; printf("%s",buffer); /* if(!strcmp(buffer,"list")) { perror("\”Server error, shut down client\n"); return EXIT_FAILURE; }*/ } while (strlen(buffer)!=0); printf("\n"); } else { printf("Error in LIST, you must login first, send command: \"LOGIN\"\n\n"); } } else if(!strcasecmp(command, "GET")) { if(strstr(file, "..")) printf("Wrong filename, filename must not contain \"..\"\n"); else c_get(create_socket, file); } else if(!strcasecmp(command, "PUT")) { c_put(create_socket, file); } else if(!strcasecmp(command, "LOGIN")) { //printf("Put wird ausgeführt\n"); if(send(create_socket, command, strlen (command), 0)==-1) perror("Error sending stuff"); do { if(read(create_socket,buffer,BUF)==-1) perror("Error reading stuff"); if(!strcmp(buffer,"log")) { login = 1; break; } } while(strcmp(buffer,"server ready")); if(!login) { clrscr(); client_auth(create_socket); } else { printf("Login refused\nAlready logged in as: %s\n\n",username); } } else if(!strcasecmp(command, "QUIT")) { printf("Client wird beendet\n"); } else { printf("Unknown command: %s\n\n", command); //error = 1; } } } while (strcasecmp (command, "QUIT") != 0); close (create_socket); } /* Ende Verbindung */ return 0; }
int main(void) { FILE *fa, *fs; /* fa指向目标文件, fs指向源文件 */ int files = 0; /* 附加的文件数量 */ char file_app[SLEN]; /* 目标文件名 */ char file_src[SLEN]; /* 源文件名 */ int ch; puts("Enter name of destination file:"); s_gets(file_app, SLEN); if ((fa = fopen(file_app, "a+")) == NULL) { fprintf(stderr, "Can't open %s\n", file_app); exit(EXIT_FAILURE); } if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't create output bueffer\n", stderr); exit(EXIT_FAILURE); } puts("Enter name of first source file (empty line to quit):"); while (s_gets(file_src, SLEN) && file_src[0] != '\0') { if (strcmp(file_src, file_app) == 0) fputs("Can't append file to itself\n", stderr); else if ((fs = fopen(file_src, "r")) == NULL) fprintf(stderr, "Can't open %s\n", file_src); else { if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't create input buffer\n",stderr); continue; } append(fs, fa); if (ferror(fs) != 0) fprintf(stderr, "Error in reading file %s.\n", file_src); if (ferror(fa) != 0 ) fprintf(stderr, "Error in writing file %s.\n", file_app); fclose(fs); files++; printf("File %s append.\n", file_src); puts("Next file(empty line to quit):"); } } printf("Done appending. %d files appended.\n", files); rewind(fa); printf("%s contents:\n", file_app); while ((ch = getc(fa)) != EOF) putchar(ch); puts("Done displaying."); fclose(fa); return 0; }
static void menu_0_1(ldr_config *conf) { wchar_t auth[MAX_PATH]; wchar_t *dp_type; char ch; do { cls_console(); if (conf->options & OP_EPS_TMO) { _snwprintf( auth, sizeof_w(auth), L"%d seconds", conf->timeout); } else { wcscpy(auth, L"disabled"); } if (conf->logon_type & LT_DSP_PASS) { dp_type = L"display \"*\""; } else { dp_type = L"disabled"; } wprintf( L"1 - On/Off \"enter password\" message (%s)\n" L"2 - Change display password type (%s)\n" L"3 - Change password prompt text (%S)\n" L"4 - Enable embedded keyfile (%s)\n" L"5 - Change authentication timeout (%s)\n" L"6 - Cancel timeout if any key pressed (%s)\n" L"7 - Return to main menu\n\n", on_off(conf->logon_type & LT_MESSAGE), dp_type, conf->eps_msg, conf->logon_type & LT_EMBED_KEY ? L"enabled":L"disabled", auth, on_off(conf->options & OP_TMO_STOP)); if ( (ch = getchr('1', '7')) == '7' ) { break; } if (ch == '1') { set_flag( conf->logon_type, LT_MESSAGE, onoff_req()); } if (ch == '2') { wprintf( L"1 - disabled\n" L"2 - display \"*\"\n"); if (getchr('1', '2') == '2') { conf->logon_type |= LT_DSP_PASS; } else { conf->logon_type &= ~LT_DSP_PASS; } } if (ch == '3') { wprintf(L"Enter new prompt text: "); s_gets(conf->eps_msg, sizeof(conf->eps_msg)); } if (ch == '4') { wchar_t path[MAX_PATH]; u8 *keyfile; u32 keysize; wprintf(L"Please enter path to keyfile: "); zeroauto(&conf->emb_key, sizeof(conf->emb_key)); conf->logon_type &= ~LT_EMBED_KEY; conf->logon_type |= LT_GET_PASS; if (s_wgets(path, sizeof(path)) != 0) { if (load_file(path, &keyfile, &keysize) != ST_OK) { wprintf(L"keyfile not loaded\n"); Sleep(1000); } else { if (keysize != 64) { wprintf(L"Embedded keyfile must be 64byte size\n"); Sleep(1000); } else { wprintf( L"1 - Use embedded keyfile and password\n" L"2 - Use only embedded keyfile\n"); if (getchr('1', '2') == '2') { conf->logon_type &= ~LT_GET_PASS; } autocpy(&conf->emb_key, keyfile, sizeof(conf->emb_key)); conf->logon_type |= LT_EMBED_KEY; } zeromem(keyfile, keysize); free(keyfile); } } } if (ch == '5') { wprintf(L"Enter new timeout in seconds or 0 to disable: "); if (wscanf(L"%d", &conf->timeout) == 0) { conf->timeout = 0; } set_flag( conf->options, OP_EPS_TMO, (conf->timeout != 0)); } if (ch == '6') { set_flag( conf->options, OP_TMO_STOP, onoff_req()); } } while (1); }
static void menu_0_2(ldr_config *conf) { wchar_t *action; char inv_msg[MAX_PATH]; int msgf, i, j; char ch; do { cls_console(); action = L"halt system"; if (conf->error_type & ET_REBOOT) { action = L"reboot system"; } if (conf->error_type & ET_BOOT_ACTIVE) { action = L"boot from active partition"; } if (conf->error_type & ET_EXIT_TO_BIOS) { action = L"exit to BIOS"; } if (conf->error_type & ET_RETRY) { action = L"retry authentication"; } if (conf->error_type & ET_MBR_BOOT) { action = L"load boot disk MBR"; } for (i = 0, j = 0; i < sizeof(conf->err_msg); i++) { if (conf->err_msg[i] != '\n') { inv_msg[j++] = conf->err_msg[i]; } } inv_msg[j] = 0; wprintf( L"1 - On/Off invalid password message (%s)\n" L"2 - Invalid password action (%s)\n" L"3 - Invalid password message (%S)\n" L"4 - Return to main menu\n\n", on_off(conf->error_type & ET_MESSAGE), action, inv_msg); if ( (ch = getchr('1', '4')) == '4' ) { break; } if (ch == '1') { set_flag( conf->error_type, ET_MESSAGE, onoff_req()); } if (ch == '2') { wprintf( L"1 - halt system\n" L"2 - reboot system\n" L"3 - boot from active partition\n" L"4 - load boot disk MBR\n" L"5 - exit to BIOS\n" L"6 - retry authentication\n"); msgf = (conf->error_type & ET_MESSAGE); switch (getchr('1', '6')) { case '1': conf->error_type = 0; break; case '2': conf->error_type = ET_REBOOT; break; case '3': conf->error_type = ET_BOOT_ACTIVE; break; case '4': conf->error_type = ET_MBR_BOOT; break; case '5': conf->error_type = ET_EXIT_TO_BIOS; break; case '6': conf->error_type = ET_RETRY; break; } conf->error_type |= msgf; } if (ch == '3') { size_t sz; wprintf(L"Enter new message text: "); if (s_gets(conf->err_msg, sizeof(conf->err_msg) - 2) != 0) { sz = strlen(conf->err_msg); conf->err_msg[sz] = '\n'; conf->err_msg[sz+1] = 0; } } } while (1); }
int main(void) { struct book library[MAXBKS]; /* 结构数组 */ int count = 0; int index, filecount; FILE * pbooks; int size = sizeof(struct book); if ((pbooks = fopen("book.dat", "a+b")) == NULL) { fputs("Can't open book.dat file\n", stderr); exit(1); } rewind(pbooks); /* 定位到文件开始 */ while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) { if (count == 0) puts("Current contents of book.dat:"); printf("%s by %s: $%.2f\n", library[count].title, library[count].author, library[count].value ); count++; } filecount = count; if (count == MAXBKS) { fputs("The book.dat file is full.", stderr); exit(2); } puts("Please add new book titles."); puts("Press [enter] at the start of a line to stop."); while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] !='\0') { puts("Now enter the author."); s_gets(library[count].author, MAXAUTL); puts("Now enter the value."); scanf("%f", &library[count++].value); while (getchar() !='\n') continue; if (count < MAXBKS) puts("Enter the next title."); } if (count > 0) { puts("Here is the list of your books:"); for (index = 0; index < count; index++) printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value ); fwrite(&library[filecount], size, count - filecount, pbooks); } else puts("No books? Too bad.\nn"); puts("Bye.\n"); return 0; }