warning: the ‘gets' function is dangerous and should not be used


今日、LINUXでCプログラムをコンパイルしたとき、警告が表示されました.
In function ‘main’:
warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
   gets(s);
   ^
/tmp/ccWcGgsb.o: In function `main':
(.text+0x3a): warning: the `gets' function is dangerous and should not be used.

warning: the 'gets' function is dangerous and should not be used.このような1つの警告は、資料を調べて自分の努力を経て、やっと問題がプログラムの中でgets()関数を使ったことを知って、Linuxの下でgccコンパイラはこの関数を支持しないで、解決方法はfgetsを使って、同時にプログラムに対して少し修正すればいいです.
まず、fgets()関数の基本的な使い方を少し理解します.
fgets(char * s,int size,FILE * stream);//eg:fgets(tempstr,10,stdin)/tempstrをchar[]変数、10を入力する文字列長、stdinを標準端末から入力できます.
 
次は、ツリーに関する小さな練習です.
#include <stdio.h>
#include <stdlib.h>

struct tree{
	char info;
	struct tree *left;
	struct tree *right;
};

struct tree *root;
struct tree *construct(struct tree *root, struct tree *r, char info);
void print(struct tree *r);

int main(void){
	char s[10];
	root = NULL;
	do{
		printf("       :");
		fgets(s, 10, stdin);
		/* gets(s); */
		root = construct(root, root, *s);
	}while(*s);
	print(root);
	return 0;
}

struct tree *construct(struct tree *root, struct tree *r, char info){
	if(!r){
		r = (struct tree *)malloc(sizeof(struct tree));
		if(!r){
			printf("      !
"); exit (0); } r->left = NULL; r->right = NULL; r->info = info; if(!root){ return r; } if(info < root->info){ root->left = r; } else{ root->right = r; } return root; } if(info < r->info){ construct(r, r->left, info); } else{ construct(r, r->right, info); } return root; } void print(struct tree *r){ int i; if(!r){ return; } print(r->left); printf("%c
", r->info); print(r->right); }

 
以上、gets()関数のみを変更しました.コンパイル中にエラーや警告は発生しませんが、実行中にプログラムをdo.whileループから飛び出すフラグ(またはステータス)が見つかりません.これは、getsが端末から読み込んだ文字列が0で終了し、fgetsが終了することが重要です.(一般的に入力はENTERで終わります)、strcmpの両方の場合は等しくありません!
だから、whileの判断条件を少し修正しなければなりません.while(*s&*s!=')に変更すればいいです.
 
課外:この問題はlinuxとwindowsのファイルが改行文字で符号化されているためで、linuxの改行は0で、windowsの改行は130で、2文字です.
しかし、ファイルはwindowsでコンパイルされるべきなので、2文字の不一致が発生します.linux端末でdos 2 unix filenameを利用して改行文字を処理することをお勧めします.