面向行fgets()和fputs()
Created|Updated
|Post Views:
前言
该函数是面向行操作。
不同于,getc()是处理字符
函数
fgets()
- 参数
(字符串地址,字符个数,FILE指针)
- 返回值
如果读到文件结尾(EOF),返回NULL
如果还没有到EOF,返回之前传给它的字符串地址
- 范围
1.读取到第一个换行符后面。
2.读到文件结尾
3.读到字符个数-1
4.如果读到字符上限已经读完一行,则会把结尾的’\n’放在’\0’前面
最后,在最后一个字符后面加’\0’
Don’t forget !
字符串的大小是:字符个数+最后的空字符
fputs()
fgets()保留了换行符,fputs()不会再添加换行符
不同于puts()函数会在末尾添加换行符
strstr()
参数
(被查找的字符串str1,需要的字符串str2)
返回值
返回str1中str2的首位置
示例
显示含有某个字符的一整行1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #include<stdio.h> #include<stdlib.h> #define SIZE 256 int has_ch(char ch, const char * line); int main(int argc, char *argv[]) { FILE *fp; char ch; char line[SIZE]; if (argc != 3) { printf("Usage: filename"); exit(EXIT_FAILURE); } ch = argv[1][0]; if ((fp = fopen(argv[2], "r")) == NULL) exit(EXIT_FAILURE);
while(fgets(line, SIZE, fp) != NULL) { if (has_ch(ch, line)) fputs(line, stdout); } fclose(fp); return 0; } int has_ch(char ch, const char * line) { while(*line) if(ch == *(line++)) return(1); return 0; }
|
交换地输出两个文件的每一行1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 40 #define LEN 256 char * s_gets(char * st, int n); int main() { char name1[SIZE]; char name2[SIZE]; FILE * f1, *f2; char *temp1; char *temp2; char str[LEN];
printf("Enter the first file: "); s_gets(name1, SIZE); printf("Enter the second file: "); s_gets(name2, SIZE);
if((f1 = fopen(name1, "r")) == NULL) { fprintf(stderr, "Could not open the %s file", name1); exit(EXIT_FAILURE); } if((f2 = fopen(name2, "r")) == NULL) { fprintf(stderr, "Could not open the %s file", name2); exit(EXIT_FAILURE); }
do { if((temp1 = fgets(str, LEN, f1)) != NULL) fputs(str, stdout); if((temp2 = fgets(str, LEN, f2)) != NULL) fputs(str, stdout);
} while ((temp1 != NULL) || (temp2 != NULL)); fclose(f1); fclose(f2); return 0; }
|
在文件中查找字符1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include<stdio.h> #include<stdlib.h> #include<string.h> #define LEN 256 int main(int argc, char *argv[]) { FILE *fp; char str[LEN];
if(argc != 3) { fprintf(stderr,"Usage: %s filename", argv[0]); exit(EXIT_FAILURE); } if((fp = fopen(argv[2], "r")) == NULL) { fprintf(stderr, "Could not open %s file", argv[2]); exit(EXIT_FAILURE); } while(fgets(str, LEN, fp) != NULL) { if(strstr(str, argv[1])) { fputs(str, stdout); } } if(fclose(fp) != 0) fprintf(stderr, "Error for closing file.\n"); return 0; }
|