開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料、light版)
- 言語: C
- コンパイラ: UNIX ccコンパイラ (汎用UNIX)
『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) II部(単純なプログラミング)の14章(ファイルの入出力)14.10(プログラミング実習/O)実習14-6を解いてみる。
実習14-6.
コード(TextWrangler)
sample.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
struct mailing{
char name[60];
char address1[60];
char address2[60];
char city[40];
char state[2];
long int zip;
};
char line[100];
FILE *out_file;
struct mailing mail;
out_file = fopen("mailing.txt", "w");
if(out_file == NULL){
fprintf(stderr, "Cannot open %s\n", "mailing.txt");
exit(8);
}
printf("name: ");
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
strcpy(mail.name, line);
printf("address1: ");
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
strcpy(mail.address1, line);
printf("address2: ");
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
strcpy(mail.address2, line);
printf("city: ");
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
strcpy(mail.city, line);
printf("state: ");
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
strcpy(mail.state, line);
printf("zip: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%ld", &mail.zip);
fprintf(out_file,
"name: %s\naddress1: %s\naddress2: %s\ncity: %s\nstate: %s\nzip: %ld\n",
mail.name, mail.address1, mail.address2, mail.city, mail.state, mail.zip);
fclose(out_file);
return (0);
}
入出力結果(Terminal)
$ cc -g -o sample sample.c $ ./sample name: kamimura address1: abcde address2: fghij city: klmno state: pq zip: 12345 $ cat mailing.txt name: kamimura address1: abcde address2: fghij city: klmno state: pq zip: 12345 $
こういう感じでいいのかな。。
0 コメント:
コメントを投稿