麻烦跑一下看看哪里有错呀#includestdio.h#includectype.h#includestdlib.h#includestring.hint m
麻烦跑一下看看哪里有错呀
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
FILE *file_sou,*file_typ;
char ch,name_sou[20],name_typ[20];
printf("Please enter the source file:\n");
gets(name_sou);
printf("Please enter the copy file:\n");
gets(name_typ);
if((file_sou=fopen(name_sou,"r"))==NULL)
{
printf("Can't open the file %s.\n",name_sou);
exit(1);
}
if((file_typ=fopen(name_typ,"w"))==NULL)
{
printf("Can't open the file %s.\n",name_typ);
exit(2);
}
while(ch=getc(file_sou))
if(toupper(ch))
putc(ch,file_typ);
fclose(file_sou);
fclose(file_typ);
return 0;
}
麻烦运行下,始终无法打开文件。。为什么?哪里出错了呀?
[解决办法]使用fread函数从File*中读数据
以下为互联网搜索:
简介
函数原型:
size_tfread(void*buffer,size_tsize,size_tcount,FILE*stream);
功 能:
从一个文件流中读数据,读取count个元素,每个元素size字节.如果调用成功返回count.返回实际读取的个数。如不成功,返回实际读取的元素个数,小于count.
参 数:
buffer
用于接收数据的内存地址,大小至少是size*count字节.
size
单个元素的大小,单位是字节
count
元素的个数,每个元素是size字节.
stream
输入流
返回值:
实际读取的元素个数.如果返回值与count不相同,则可能文件结尾或发生错误.
从ferror和feof获取错误信息或检测是否到达文件结尾.
程序例
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];
if ( (stream = fopen("DUMMY.FIL", "w+")) == NULL) {
fprintf(stderr,"Cannot open output file.\n");
return 1;
} /* write some data to the file */
fwrite(msg, 1,strlen(msg)+1, stream); /* sizeof(char)=1 seek to the beginning of the file */[1]
fseek(stream, 0, SEEK_SET); /* read the data and display it */
fread(buf, 1,strlen(msg)+1,stream);
printf("%s\n", buf);
fclose(stream);
return 0;
}
MSDN示例
#include <stdio.h>
void main( void )
{
FILE *stream;
char list[30];
int i, numread, numwritten; /* Open file in text mode: */
if( (stream = fopen( "fread.out", "w+t" )) != NULL )
{
for ( i = 0; i < 25; i++ )
list[i] = (char)('z' - i); /* Write 25 characters to stream */
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );
}
else
printf( "Problem opening the file\n" );
if( (stream = fopen( "fread.out", "r+t" )) != NULL )
{ /* Attempt to read in 25 characters */
numread = fread( list, sizeof( char ), 25, stream );
printf( "Number of items read = %d\n", numread );
printf( "Contents of buffer = %.25s\n", list );
fclose( stream );
}
else
printf( "File could not be opened\n" );
}