//從鍵盤輸入一串字符,將其中的小寫字母轉爲
//大寫字母並存入名爲test.txt的文件中
//輸出轉換後的字符串
//打開文件:fopen("文件名","操作方式");
//操作方式可以使w 只寫, r 只讀等等
//打開失敗返回NULL,成功返回文件地址
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char str[100];
int i=0;
if((fp=fopen("test.txt","w"))==NULL)
{
printf("cant open\n");
}
printf("input a string:\n");
gets(str);
while(str[i]!='!')
{
if(str[i]>='a'&&str[i]<='z')
str[i]=str[i]-32;
fputc(str[i],fp);
i++;
}
fclose(fp);
fgets(str,strlen(str)+1,fp);
printf("%s\n",str);
fclose(fp);
return 0;
}
//從一個已經存在的文件中讀取字符
//讀取成功則返回讀取到的字符
//fgetc(fp) 只有一個參數,即文件指針
#include<stdio.h>
#include<string.h>
int main()
{
char str[101],b[101];
FILE *fp,*fp1;
//這裏要把文件放在.cpp的相同文件夾裏
//或者寫出文件的絕對路徑,不能有漢字
fp=fopen("test.txt","r");
//方法一,逐個讀取 fgetc()
int i=0;
while(!feof(fp)) str[i++]=fgetc(fp);
for(int j=0;j<i;j++) printf("%c",str[j]);
printf("\n");
//方法二,整體讀取fgets()
fp1=fopen("test (2).txt","r");
fgets(b,130,fp1);
puts(b);
return 0;
}