C语言上机调试之文件
主程序:
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp;
int i,j,n,i1;
char c[100],t,ch;
if((fp=fopen( "A ", "r "))==NULL)
{
printf( "\ncan not open file\n ");
exit(0);
}
printf( "file A:\n ");
for(i=0;(ch=fgetc(fp))!=EOF;i++)
{
c[i]=ch;
putchar(c[i]);
}
fclose(fp);
i1=i;
if((fp=fopen( "B ", "r "))==NULL)
{printf( "\ncan not open file\n ");
exit(0);
}
printf( "\nfile B:\n ");
for(i=i1;(ch=fgetc(fp))!=EOF;i++)
{
c[i]=ch;
putchar(c[i]);
}
fclose(fp);
n=i;
for(i=0;i <n;i++)
for(j=i+1;j <n;j++)
if(c[i]> c[j])
{t=c[i];
c[i]=c[j];
c[j]=t;}
printf( "\nfile C:\n ");
fp=fopen( "C ", "w ");
for(i=0;i <n;i++)
{putc(c[i],fp);
putchar(c[i]);
}
printf( "\n ");
fclose(fp);
}
用于生成内容为“i love china "和 "i love beijing "的文件的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE *fp;
char str[40];
int i=0;
if((fp=fopen( "A ", "w "))==NULL)
{
printf( "can not open file\n ");
exit(0);
}
printf( "input a string:\n ");
gets(str);
while(str[i]!= '\n ')
{
if (str[i]> = 'a '&&str[i] <= 'z ')
str[i]=str[i]-32;
fputc(str[i],fp);
i++;
}
fclose(fp);
//fp=fopen( "A ", "r ");
//fgets(str,i,fp);
printf( "%s\n ",str);
//fclose(fp);
}
另一个是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE *fp;
char str[40];
int i=0;
if((fp=fopen( "B ", "w "))==NULL)
{
printf( "can not open file\n ");
exit(0);
}
printf( "input a string:\n ");
gets(str);
while(str[i]!= '\n ')
{if (str[i]> = 'a '&&str[i] <= 'z ')
str[i]=str[i]-32;
fputc(str[i],fp);
i++;
}
fclose(fp);
//fp=fopen( "B ", "r ");
//fgets(str,strlen(str)+1,fp);
printf( "%s\n ",str);
//fclose(fp);
}
运行结果里有乱码,在字符串a和b的末尾还分别有 ":B ",不知道怎么回事,哪里有
问题,请大家帮忙!
[解决办法]
你的最后一段代码运行后 B文件 里面有乱码
把while(str[i]!= '\n ')改成while(str[i]!= '\0 ')
字符串是以 '\0 '结尾的