㈠ 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] = '