本文目錄一覽:
- 1、C語言讀取文件問題
- 2、c語言將文件的第二(以及第n)行讀入一個字符串的做法。
- 3、C語言 fgets函數讀取CSV文件如何從第二行開始,第一行是表頭。
- 4、求個C語言程序 讀取TXT文件第二行(隨機換行)數據
- 5、c語言如何讀取txt文件的前2兩行
C語言讀取文件問題
#include stdio.h
main()
{
FILE *fp = fopen(“data.txt”,”r”);
char str[20]={0},str1[20]={0};
int i,x,y,z;
fgets(str,sizeof(str),fp);
printf(“str=%s”,str);
fgets(str1,sizeof(str1),fp);
sscanf(str1,”%d %d %d”,x,y,z);
printf(“x=[%d] y=[%d] z=[%d]\n”,x,y,z);
printf(“replace\n”);
for (i=0;str[i]!=’\0′;i++)
{
if (str[i]==’x’)
{
str[i] = x+48;
}
if (str[i]==’y’)
{
str[i] = y+48;
}
if (str[i]==’z’)
{
str[i] = z+48;
}
}
printf(“str=%s\n”,str);
fclose(fp);
}
str=(x+y)*5-z
x=[3] y=[4] z=[5]
replace
str=(3+4)*5-5
Press any key to continue
c語言將文件的第二(以及第n)行讀入一個字符串的做法。
#include stdio.h
int main()
{
FILE *fp;
int ch;
char a[128];
fp=fopen( “123.txt” , “r” );
if ( fp )
{
do {
ch=fgetc(fp);
} while( ch!=’\n’ ) ; //跳過一行,以’\n’為換行符
fgets( a,sizeof(a),fp );
printf(“a=%s” , a );
fclose(fp);
}
return 0;
}
C語言 fgets函數讀取CSV文件如何從第二行開始,第一行是表頭。
第一次獲取的數據不要就可以了,何必這麼麻煩。
函數原型:
char *fgets(char *buf, int bufsize, FILE *stream);
參數:
*buf: 字符型指針,指向用來存儲所得數據的地址。
bufsize: 整型數據,指明存儲數據的大小。
*stream: 文件結構體指針,將要讀取的文件流。
返回值:
成功,則返回第一個參數buf;
在讀字符時遇到end-of-file,則eof指示器被設置,如果還沒讀入任何字符就遇到這種情況,則buf保持原來的內容,返回NULL;
如果發生讀入錯誤,error指示器被設置,返回NULL,buf的值可能被改變。
例子:
#includestring.h
#includestdio.h
int main ( void )
{
FILE*stream;
char string[]=”Thisisatest”;
char msg[20];
/*openafileforupdate*/
stream=fopen(“DUMMY.FIL”,”w+”);
/*writeastringintothefile*/
fwrite(string,strlen(string),1,stream);
/*seektothestartofthefile*/
fseek(stream,0,SEEK_SET);
/*readastringfromthefile*/
fgets(msg,strlen(string)+1,stream);
/*displaythestring*/
printf(“%s”,msg);
fclose(stream);
return 0;
}
求個C語言程序 讀取TXT文件第二行(隨機換行)數據
#include stdio.h
#include string.h
void main()
{
int i,n;
char str[500];
FILE *fp;
printf(“請輸入需要讀取第幾行數據\n”);
scanf(“%d”, n);
if((fp=fopen(“test.txt”,”rt”))==NULL) /* 假設在程序目錄下,文件名為test.txt */
{
printf(“cannot open file\n”);
return;
}
for(i=1;in;i++)
fscanf(fp,”%*[^\n]%*c”); /* 跳過一行字符串 */
fscanf(fp,”%[^\n]%*c”,str);/* 讀入一行字符串 */
printf(“%s\n”, str);
fclose(fp);
}
c語言如何讀取txt文件的前2兩行
看在足球的份上,幫你寫了一個參考代碼,自己研究一下吧
#include stdio.h
int main()
{
FILE *fp ;
char str[1000];
int max;
int player, score, timein, round;
fp=fopen(“TXT”, “r” ); //注意調整文件名
if( fp==NULL )
{
printf(“open file erorr\n”);
return -1;
}
fgets(str, sizeof(str), fp ); //讀第一行
sscanf(str,”%d”, max );
while( fgets(str, sizeof(str), fp )) //讀其餘行
{
sscanf(str, “%d%d%d%d”, player, round, timein, score ); //從字符串讀取相關數據
printf(“玩家: %02d 得分: %3d 上場時間: %5d 場次: %02d\n”,
player, score, timein, round );
}
fclose(fp);
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/192503.html