本文共 2511 字,大约阅读时间需要 8 分钟。
[root@db-172-16-3-150 zzz]# cat n.c#include#include char a[10];int main() { printf("enter a word:"); fgets(a,sizeof(a),stdin); // 使用stdin作为输入, fgets限定长度时使用sizeof(a) 不需要去除\0. scanf和fscanf使用%10s限定长度时表示存储10个字符(不包括\0, 所以要sizeof(a)-1) printf("a:%s\n", a); return 0;}结果[root@db-172-16-3-150 zzz]# gcc -O3 -Wall -Wextra -Werror -g ./n.c -o n && ./nenter a word:abc def ghia:abc def g
[root@db-172-16-3-150 zzz]# cat n.c#include在测试时遇到几个问题, 请教了诸位C高手后,记录一下.#include #include #include int main() { char a[10]; char w_file[] = "/root/zzz/out.txt"; char w_mode[] = "w"; FILE *out = fopen(w_file,w_mode); printf("enter a word:"); fgets(a,sizeof(a),stdin); fprintf(out,"a:%s\n", a); // 输出到文件 return 0;}结果[root@db-172-16-3-150 zzz]# gcc -O3 -Wall -Wextra -Werror -g ./n.c -o n && ./nenter a word:abcdefghijkl[root@db-172-16-3-150 zzz]# cat out.txta:abcdefghi
#include#include #include #include void output(FILE * out,char * a) { fprintf(out,"a:%s\n", a); close(fileno(out));}char a[10];char w_file[] = "/root/zzz/out.txt";char w_mode[] = "w";//FILE *out = fopen(w_file,w_mode);int main() { FILE *out = fopen(w_file,w_mode); printf("enter a word:"); fgets(a,sizeof(a),stdin); output(out,a); return 0;}
#include#include #include #include #include void output(FILE * lout,char * la) { fprintf(lout,"a:%s\n", la); if (fsync(fileno(lout))) { printf("error:%s\n", strerror(errno)); }}char a[10];char w_file[] = "/root/zzz/out.txt";char w_mode[] = "w";FILE *out;int main() { out = fopen(w_file,w_mode); printf("enter a word:"); fgets(a,sizeof(a),stdin); output(out,a); fclose(out); return 0;}
转载地址:http://rqmix.baihongyu.com/