本文目錄一覽:
C語言讀取txt文件內容
#include stdio.h
#include stdlib.h
int main()
{
FILE *file;
char *data;
int fileSize;
// 打開文件「D:\a.txt」
file = fopen(“D:\\a.txt”, “r”);
// 獲得文件大小
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
// 分配內存
data = (char*)malloc(fileSize + 1);
// 讀取文件
fread(data, sizeof(char), fileSize, file);
data[fileSize] = 0;
// 輸出內容(你想對內容幹什麼都可以了)
printf(“%s”, data);
return 0;
}
c語言在txt查找文本,返回相同的行的數據
#includestdio.h
struct RECs { unsigned int uRoomID,uID,uBoth; char sStyle[20]; };
void main() { struct RECs a; FILE *fp; char buffer[256]; unsigned int r; int b;
if ( fp=fopen(“c:\\room.txt”,”r”) ) {
while ( 1 ) {
printf(“請輸入ROOM ID: “); scanf(“%u”,r); if ( r==0 ) break;
fseek(fp,0L,SEEK_SET); b=0;
while ( !feof(fp) ) {
fgets(buffer,255,fp); sscanf(“%u%s%u%u”,a.uRoomID,a.sStyle,a.uID,a.uBoth);
if ( uRoomID==r ) {
printf(“ID=%u,STYLE=%s,ID=%u,BOTH=%u\n”,a.uRoomID,a.sStyle,a.uID,a.uBoth);
b=1;
break;
}
}
if ( b==0 ) printf(“沒有該房間記錄。\n”); else printf(“\n”);
}
fclose(fp);
} else printf(“無法打開文件讀取數據。\n”);
}
C語言如何讀取txt文本裏面的內容?
FILE *fp = fopen(“D:\\1.txt”, “r”);
int a,b;
while(fscanf(fp, “%d,%d”) != EOF)
printf(“%d %d\n”, a,b);
fclose(fp);
fscanf(fp, “%d,%d”)
這個是讀文件的函數。
在c語言中,如何讀取一個txt文件中的信息
一般來說在C語言中讀取txt文件的信息有兩種方法,一種是使用C語言標準文件I/O中的fopen()、fread()等等函數,一種是調用操作系統中的API函數,比如Windows上的ReadFile()、OpenFile()等等,現在操作系統一般都具備內存文件映射功能,對於大的txt文件,一般都使用這種方式操作。下面是一個使用C語言標準文件I/O操作文件的例子。
#includestdio.h
FILE*stream;
void main(void)
{
long l;
float fp;
char s[81];
char c;
stream=fopen(“fscanf.out”,”w+”);
if(stream==NULL)
printf(“Thefilefscanf.outwasnotopened\n”);
else
{
fprintf(stream,”%s%ld%f%c”,”hello world”,
65000,3.14159,’x’);
/*Setpointertobeginningoffile:*/
fseek(stream,0L,SEEK_SET);
/*Readdatabackfromfile:*/
fscanf(stream,”%s”,s);
fscanf(stream,”%ld”,l);
fscanf(stream,”%f”,fp);
fscanf(stream,”%c”,c);
/*Outputdataread:*/
printf(“%s\n”,s);
printf(“%ld\n”,l);
printf(“%f\n”,fp);
printf(“%c\n”,c);
fclose(stream);
}
}
C語言中讀取txt文件內容
樓主朋友,你的程序中的問題出在分配空間不足上。比如當你想讓a[j]指向某段內存時,用的是
a[j]=(char *)malloc(sizeof(char)); 而到了後面你是要在這段內存中存入一個字符串的,所以就發生了越界。下面是我根據你的代碼片段寫的一個測試程序,經過修改應該沒問題了。
#include stdio.h
#include stdlib.h
int main (void)
{
char path[]=”12345.txt”;
FILE *create;
if((create=fopen(path,”r”))!=NULL)
{
int j; char **a;
a=(char **)malloc(100*sizeof(char*)); //此處如果只申請一個char *大小的空間時,
//你以後的a[j]往哪裡放?此處的100是假設你的文件中有100行信息。如果超過100還得多分配
for (j=0;;j++)
{
a[j]=(char *)malloc(10000*sizeof(char)); //此處只申請一個字符的空間,後面讀取
//長度為10000的字符串就沒地方存放了
fgets(a[j],10000,create);
printf(“%s”,a[j]); //測試讀取是否成功,將文件中信息顯示到屏幕上
if(feof(create)!=0)
{
for(;j=0;j–)
free(a[j]);
break;
}
}
free(a);
}
else
printf(“Fail to open the file.\n”);
fclose(create);
printf(“\n”);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/153563.html