㈠ c语言读取文本文件
1、C语言标准库提供了一系列文件操作函数。文件操作函数一般以f+单词的形式来命名(f是file的简写),其声明位于stdio.h头文件当中。例如:fopen、fclose函数用于文件打开与关闭;fscanf、fgets函数用于文件读取;fprintf、fputs函数用于文件写入;ftell、fseek函数用于文件操作位置的获取与设置。
2、例程:
#include<stdio.h>
inta;
charb,c[100];
intmain(){
FILE*fp1=fopen("input.txt","r");//打开输入文件
FILE*fp2=fopen("output.txt","w");//打开输出文件
if(fp1==NULL||fp2==NULL){//若打开文件失败则退出
puts("不能打开文件!");
rturn0;
}
fscanf(fp1,"%d",&a);//从输入文件读取一个整数
b=fgetc(fp1);//从输入文件读取一个字符
fgets(c,100,fp1);//从输入文件读取一行字符串
printf("%ld",ftell(fp1));//输出fp1指针当前位置相对于文件首的偏移字节数
fputs(c,fp2);//向输出文件写入一行字符串
fputc(b,fp2);//向输出文件写入一个字符
fprintf(fp2,"%d",a);//向输出文件写入一个整数
fclose(fp1);//关闭输入文件
fclose(fp2);//关闭输出文件,相当于保存
return0;
}
㈡ 想请教一个c语言的问题。我想从TXT文本文件中提取时间数据(数据格式为14:44:57.00)。请问如何提取。
想准确的对一个文本解析。不知道大概格式是很难的。比如:
12:13:12:13 可能是正确的数据 但是 12:12:13:45:45:34 呢?因此制作文本i必须有特定规范。"协议“。。。方便解析。这个和网络截取数据包。但是未必能解析出来一样的。但是还是能得出一部分的。对不对就不知道了。你实在要解析,可以从‘:’开始匹配。看能不能匹配出连续的像:
”XX:XX:XX:XX" 的数据,并保证时在0-23之间。。同理分秒在0-59之间,等等判断。
数据是什么类型。这个没人知道。也许别人按照int 和字符。。也许完全是字符。也许是string..结构体等等。但都可以当二进制文件访问
㈢ C语言如何读取txt文本里面的内容
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 " );
else
printf( "The file 'data' was opened " );
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened " );
else
printf( "The file 'data2' was opened " );
/* Close stream */
if(fclose( stream2 ))
printf( "The file 'data2' was not closed " );
/* All other files are closed: */
numclosed = _fcloseall( );
printf( "Number of files closed by _fcloseall: %u ", numclosed );
}
(3)c语言如何读取文本的时间扩展阅读
使用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] = '