Last active
August 28, 2019 02:16
-
-
Save oha-yashi/12c05562f0e746762c304009606eb92b to your computer and use it in GitHub Desktop.
行番号をつけるプログラムと,実行ファイル作成のためのmakefile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pln: putLineNumber.c | |
gcc -o $@ $^ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#define STR_MAX 256 | |
#define EXTENSION ".txt" /* 拡張子 */ | |
#define THIS_FILE "putLineNumber.c" | |
#define DO_FILE "pln" | |
void set_filename(int argc, char *argv[], char *set){ | |
if(argc == 2){ /* コマンドライン引数2つのとき */ | |
int dot, i; /* 拡張子の位置を表す変数 & ループ変数 */ | |
char *ret; /* '.'のアドレス */ | |
char *plus = EXTENSION; /* 拡張子 */ | |
/* 拡張子の位置('.'の位置を後ろから探索) */ | |
if ( (ret = strrchr(argv[1], '.')) != NULL ) { | |
dot = ret - argv[1]; | |
} else { | |
dot = strlen(argv[1]); | |
} | |
strncpy(set, argv[1], dot); | |
for(i=0; i<strlen(EXTENSION); i++){ | |
set[dot+i] = plus[i]; | |
} | |
}else{ /* コマンドライン引数3つ */ | |
/* プログラムと実行ファイルの破壊を防ぐ */ | |
if( strcmp(argv[2], THIS_FILE) == 0 || strcmp(argv[2], DO_FILE) == 0 ){ | |
printf("!! can not set %s as output file name. !!\n", argv[2]); | |
strcpy(set, "output.txt"); | |
}else{ | |
strcpy(set, argv[2]); | |
} | |
} | |
} | |
void read_write(FILE *r, FILE *w){ | |
char str[STR_MAX] = {'\0'}; /* ファイル内容の収納 */ | |
int cnt = 1;/* 行番号は1から */ | |
while(fgets(str, STR_MAX, r) != NULL){/* ここで\nまで読み込んでいるので */ | |
fprintf(w, "%4d %s", cnt, str);/* ここでは\nいらない */ | |
cnt++; | |
} | |
} | |
int main(int argc, char *argv[]){ | |
FILE *fpread, *fpwrite; | |
char filename[STR_MAX] = {'\0'}; | |
/* コマンドライン引数は2つか3つ */ | |
if(argc != 2 && argc != 3){ | |
printf("!! command ERROR !!\n"); | |
return -1; | |
} | |
/* 書き込むファイル名を決める */ | |
set_filename(argc, argv, filename); | |
printf("output file name(path)\n\t%s\n\n", filename); | |
fpread = fopen(argv[1], "r"); | |
if(fpread == NULL){ | |
printf("!! read file open ERROR !!\n"); | |
return -1; | |
} | |
fpwrite = fopen(filename, "w"); | |
if(fpwrite == NULL){ | |
printf("!! write file open ERROR !!\n"); | |
return -1; | |
} | |
/* 書き込み */ | |
printf("start reading\n\t%s\n\n", argv[1]); | |
read_write(fpread, fpwrite); | |
printf("end writing\n\t%s\n\n", filename); | |
fclose(fpread); | |
fclose(fpwrite); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/oha-yashi/gist_public