C 言語演習 解説

Download Report

Transcript C 言語演習 解説

C言語演習
情報ネットワーク特論
C言語プログラミング
• エディタ
– vi, emacs
• コンパイラ (リンカ)
• gcc
• 関数名、ヘッダファイルを探す
– man コマンド
– 検索
C言語プログラミング・課題
1. ファイルを読み込んで、その内容を表示する
プログラムを作成せよ。
2. キーボードから文字を入力して、その内容を
ファイルに書き込むプログラムを作成せよ。
3. ファイルから数字を読み込んで、ソートする
プログラムを作成せよ。
4. キーボードから数字を入力して、入力後、
ソートするプログラムを作成せよ。
ファイルを読み込んで、その内容を表示するプログラムを作成せよ。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main(narg,arg)
int narg;
char **arg;
{
int fd;
char ch;
fd=open(arg[1],O_RDONLY);
if(fd<0){
perror("File Name");
exit(EXIT_FAILURE);
}
while(read(fd,&ch,sizeof(char)))
printf("%c",ch);
close(fd);
}
キーボードから文字を入力して、その内容をファイルに書き込むプログラムを作成せよ。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
while(1){
ch=getchar();
if(ch==EOF)
break;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
write(fd,&ch,sizeof(char));
main(narg,arg)
int narg;
char **arg;
{
}
close(fd);
}
int fd;
char ch;
fd=open(arg[1],O_WRONLY|O_APPEND |O_CREAT);
if(fd<0){
perror("File Name");
exit(EXIT_FAILURE);
}
ファイルから数字を読み込んで、ソートするプログラムを作成せよ。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main(narg,arg)
int narg;
char **arg;
{
FILE *fd;
char ch;
int num[1024];
int n=0;
int i,j;
fd=fopen(arg[1],"r");
if(fd == NULL){
perror("File Name");
exit(EXIT_FAILURE);
}
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++){
if(num[i] > num[j]){
int tmp;
tmp=num[j];
num[j]=num[i];
num[i]=tmp;
}
}
while(1){
char buf[128];
if(fgets(buf,128,fd)==NULL)
break;
sscanf(buf,"%d",&num[n]);
n++;
}
printf("\nAfter\n");
for(i=0;i<n;i++)
printf("%d\n",num[i]);
printf("Before\n");
for(i=0;i<n;i++)
printf("%d\n",num[i]);
fclose(fd);
}