c语言中怎么在屏幕上输入文件名然后从此文件中读取内容到屏幕?

c语言中怎么在屏幕上输入文件名然后从此文件中读取内容到屏幕?,第1张

#include <stdio.h>#include <string.h>void   main(){    int    n    double x,y,z/* 如果需要保存每次数据,可以用数组 */        FILE   *fp        char   filename[100]        char  str[1000]printf("\nEnter a filepath/filename:\n")        gets(filename) 晌裂  弯稿 fp=fopen(filename, "rt")        if(fp==NULL)        {  宴闹闭            printf("cannot open file\n")              return        }        while (fgets(str,1000,fp))  //读取一行,并判断文件是否结束        {        sscanf(str,"%d,%lf,%lf,%lf\n",&n,&x,&y,&z)        printf("%d,%e,%e,%e\n",n,x,y,z)      }       fclose(fp)}

C语言可以使用fopen()函数读取txt文本羡旅明里。

示例镇睁:

#include <stdio.h>

FILE *stream, *stream2

void main( void )

{

int numclosed

/* Open for read (will fail if file "data" does not exist) */

if( (stream  = fopen( "data", "r" )) == NULL )

printf( "The file 'data' was not opened\n" )

else

printf( "The file 'data' was opened\n" )

/* Open for write */

if( (stream2 = fopen( "data2", "w+" )) == NULL )

printf( "The file 'data2' was not opened\n" )

else

printf( "The file 'data2' was opened\n" )

/* Close stream */

if(fclose( stream2 ))

printf( "The file 'data2'兄告 was not closed\n" )

/* All other files are closed: */

numclosed = _fcloseall( )

printf( "Number of files closed by _fcloseall: %u\n", numclosed )

}

扩展资料

使用fgetc函数

#include <stdio.h>

#include <stdlib.h>

void main( void )

{

FILE *stream

char buffer[81]

int  i, ch

/* Open file to read line from: */

if( (stream = fopen( "fgetc.c", "r" )) == NULL )

exit( 0 )

/* Read in first 80 characters and place them in "buffer": */

ch = fgetc( stream )

for( i=0(i <80 ) &&( feof( stream ) == 0 )i++ )

{

buffer[i] = (char)ch

ch = fgetc( stream )

}

/* Add null to end string */

buffer[i] = '\0'

printf( "%s\n", buffer )

fclose( stream )

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12130513.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存