版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/89575696
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//fputc()不在字符后面添加换行
//fgetc()不在字符后面添加换行,不管这个字符后面是不是换行,它只读取一个字符
//fputs()不在字符后面添加换行
//fgets()读取文件一行内容,行尾无换行则无换行,有换行读取换行
//一般情况下向文件中写数据都在行末添加一个换行(fputc('\n', fp)),这样每次都是从新的一行写入数据
//当从文件中读取数据时,如果文件一行后面回车了,则读出的字符串后面添加一个换行符否则没有
//注意文件中的换行符是属于上一行的
//scanf()读取后向文件中fputs不写入换行符
int main()
{
FILE *fp1, *fp2;
char str[50];
char s[6][50];
//向文件中写入字符串
fp1=fopen("D:\\myfile", "w");
if (fp1==NULL){
printf("cannot open\n");
exit(-1);
}
scanf("%s", str); //不读入字符串结尾的换行符
fputs(str, fp1); //不自动添加换行符
fclose(fp1);
//从文件中读取字符串
fp1=fopen("D:\\myfile", "r");
if (fp1==NULL){
printf("cannot open\n");
exit(-1);
}
fgets(str, 50, fp1);
printf("%s", str);
fclose(fp1);
//作业1:从磁盘文件file1.txt中读出这行字符串,将其中的小写字母全改成
// 大写字母,输出到磁盘文件file2.txt
fp1=fopen("D:\\file1.txt", "r");
if (fp1==NULL){
printf("cannot open\n");
exit(-1);
}
fgets(str, 50, fp1);
int len=strlen(str);
for (int i=0; i<len; i++)
if (str[i]>='a'&&str[i]<='z')
str[i]=str[i]-'a'+'A';
printf("%s", str);
fclose(fp1);
//作业2:从磁盘读入5字符串,对他们按照字母大小的顺序排序,然后把排好序的
// 字符串送到磁盘文件string.txt中保存
//这里假定5个字符串长度一样
fp1=fopen("D:\\file1.txt", "r");
fp2=fopen("D:\\file2.txt", "w");
if (fp1==NULL || fp2==NULL){
printf("open failed\n");
exit(-1);
}
for (int i=1; i<=5; i++){
fgets(s[i], 50, fp1);
}
len=strlen(s[1]);
for (int i=1; i<=5-1; i++){
for (int j=1; j<=5-i; j++){
if(strcmp(s[j], s[j+1])>0){
char t[50];
strcpy(t, s[j]);
strcpy(s[j], s[j+1]);
strcpy(t, s[j+1]);
}
}
}
for (int i=1; i<=5; i++){
fputs(s[i], fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}