溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C 文件讀寫

發(fā)布時間:2020-07-13 08:11:05 來源:網絡 閱讀:776 作者:990487026 欄目:開發(fā)技術



r 文件只讀操作打開一個文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
        FILE *p = fopen("./test.txt","r");
        if(p == NULL)
        {
                printf("open fail! \n");
        }
        else
        {
                printf("open sucess!\n");
        }
        return 0;
}
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.4K May 27 16:09 a.out
-rw-rw-r-- 1 chunli chunli  215 May 27 16:09 main.c
-rw-rw-r-- 1 chunli chunli  209 May 27 16:04 test.txt

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!



w 文件只寫操作如果文件不存在就創(chuàng)建文件如果文件存在就清空文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
        FILE *p = fopen("write_file.txt","w");
        if(p == NULL)
        {
                printf("open fail! \n");
        }
        else
        {
                printf("open sucess!\n");
        }
        return 0;
}


chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.4K May 27 16:09 a.out
-rw-rw-r-- 1 chunli chunli  215 May 27 16:09 main.c
-rw-rw-r-- 1 chunli chunli  209 May 27 16:04 test.txt
-rw-rw-r-- 1 chunli chunli    0 May 27 16:09 write_file.txt


從文件讀幾個字符

chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 479 May 27 16:18 main.c
chunli@ubuntu:~/pointer$ cat main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
	FILE *p = fopen("main.c","r");//打開當前目錄下的文件
	if(p == NULL)
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c",c);
		c = getc(p);
		printf("%c  \n",c);
	}
	return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!


讀取文件所有字符

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        FILE *p = fopen("main.c","r");//打開當前目錄下的文件
        if(p == NULL)
        {
                printf("open fail! \n");
        }
        else
        {
                printf("open sucess!\n");
                char c = 0;
                while((c = getc(p)) != EOF)
                {
                        printf("%c",c);
                }
        }
        return 0;
}


編譯運行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
	FILE *p = fopen("main.c","r");//打開當前目錄下的文件
	if(p == NULL)
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p)) != EOF)//讀取文件所有字符  
		{
			printf("%c",c);
		}
	}
	return 0;
}



文本文件復制

chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 428 May 27 16:32 main.c

main程序
chunli@ubuntu:~/pointer$ cat main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
	FILE *p1 = fopen("main.c","r");//打開當前目錄下的文件
	FILE *p2 = fopen("text.c","w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
	return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!

可以看到生成了一個新的文件
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.6K May 27 16:33 a.out
-rw-rw-r-- 1 chunli chunli  428 May 27 16:32 main.c
-rw-rw-r-- 1 chunli chunli  428 May 27 16:33 text.c

查看這個文件
chunli@ubuntu:~/pointer$ cat text.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
	FILE *p1 = fopen("main.c","r");//打開當前目錄下的文件
	FILE *p2 = fopen("text.c","w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
	return 0;
}
chunli@ubuntu:~/pointer$



文件加密

chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 495 May 27 16:40 main.c
主程序
chunli@ubuntu:~/pointer$ cat main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void code(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c+=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
int main()
{
	code("main.c","code.txt");
}

編譯并運行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!

看看產生的文件
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.6K May 27 16:40 a.out
-rw-rw-r-- 1 chunli chunli  495 May 27 16:40 code.txt
-rw-rw-r-- 1 chunli chunli  495 May 27 16:40 main.c

已經完成加密的文件
chunli@ubuntu:~/pointer$ cat code.txt 
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*myno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴鎖 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m5G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン sx~*wksx23myno2,wksx8m,6,myno8~~,3Echunli@ubuntu:~/pointer$



文件解密

chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 923 May 27 16:43 main.c
chunli@ubuntu:~/pointer$ cat main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c-=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
void code(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c+=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
int main()
{
	code("main.c","code.txt");
	decode("code.txt","decode.txt");
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
open sucess!
chunli@ubuntu:~/pointer$ cat decode.txt 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c-=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
void code(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c+=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
int main()
{
	code("main.c","code.txt");
	decode("code.txt","decode.txt");
}
chunli@ubuntu:~/pointer$


主函數傳參數加密解密

主程序 main.c 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c-=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
void code(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c+=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
int main(int argc, char *args[])
{
	if(argc < 4)
	{
		printf("參數1:1加密1:2解密\n");
		printf("參數2:1輸入文件2:2輸出文件\n");
	}
	else
	{
		if(atoi(args[1]) == 1)
		{
			code(args[2],args[3]);
		}
		if(atoi(args[1]) == 2)
		{
			decode(args[2],args[3]);
			
		}
	}
}
編譯
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c 
執(zhí)行
chunli@ubuntu:~/pointer$ ./a.out 
參數1:1加密1:2解密
參數2:1輸入文件2:2輸出文件

執(zhí)行加密
chunli@ubuntu:~/pointer$ ./a.out 1 main.c  加密了.txt
open sucess!

執(zhí)行解密
chunli@ubuntu:~/pointer$ ./a.out 2 加密了.txt 解密了.txt
open sucess!

查看加密的文件
chunli@ubuntu:~/pointer$ cat 加密了.txt 
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*nomyno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴鎖 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m7G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン ysn*myno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴鎖 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m5G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン sx~*wksx2sx~*k|qm6*mrk|*4k|q}eg3sp2k|qm*F*>3z|sx~p2,D;僵蓾<昀碭,3Ez|sx~p2,D;螯耄仄<螯 曱碭,3Eov}osp2k~ys2k|q}e;g3*GG*;3myno2k|q}e<g6k|q}e=g3Esp2k~ys2k|q}e;g3*GG*<3nomyno2k|q}e<g6k|q}e=g3E

查看界面的文件



chunli@ubuntu:~/pointer$ cat 解密了.txt 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c-=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
void code(const char *src,const char *dest) 
{
	FILE *p1 = fopen(src, "r");//打開當前目錄下的文件
	FILE *p2 = fopen(dest,"w");//創(chuàng)建文件
	if((p1 == NULL) ||(p2 == NULL) )
	{
		printf("open fail! \n");
	}
	else
	{
		printf("open sucess!\n");
		char c = 0;
		while((c = getc(p1)) != EOF)
		{
			c+=10;
			putc(c,p2);
		}
	}
	fclose(p1);//關閉文件
	fclose(p2);//關閉文件
}
int main(int argc, char *args[])
{
	if(argc < 4)
	{
		printf("參數1:1加密1:2解密\n");
		printf("參數2:1輸入文件2:2輸出文件\n");
	}
	else
	{
		if(atoi(args[1]) == 1)
		{
			code(args[2],args[3]);
		}
		if(atoi(args[1]) == 2)
		{
			decode(args[2],args[3]);
			
		}
	}
}
chunli@ubuntu:~/pointer$



一行一行的讀取文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
	FILE *p = fopen("main.c","r");
	char buf[1024];
	while(!feof(p))//判斷是不是到了文件結束
	{
		fgets(buf,sizeof(buf),p); //從文件讀取一行
		printf("%s ",buf);
	
	}
	fclose(p);
	return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 int main(int argc, char *args[])
 {
 	FILE *p = fopen("main.c","r");
 	char buf[1024];
 	while(!feof(p))//判斷是不是到了文件結束
 	{
 		fgets(buf,sizeof(buf),p); //從文件讀取一行
 		printf("%s ",buf);
 	
 	}
 	fclose(p);
 	return 0;
 }
 }
 chunli@ubuntu:~/pointer$



文件復制 一行一行的復制

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        FILE *p1 = fopen("main.c","r");
        FILE *p2 = fopen("cpoy.txt","w");
        char buf[1024];
        while(!feof(p1))//判斷是不是到了文件結束
        {
                fgets(buf,sizeof(buf),p1);//從文件中讀取
                fputs(buf,p2);//寫入到另一個文件
        }
        fclose(p1);
        fclose(p2);
        return 0;
}


chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.7K May 27 18:51 a.out
-rw-rw-r-- 1 chunli chunli  325 May 27 18:51 cpoy.txt
-rw-rw-r-- 1 chunli chunli  323 May 27 18:51 main.c
chunli@ubuntu:~/pointer$ cat cpoy.txt 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        FILE *p1 = fopen("main.c","r");
        FILE *p2 = fopen("cpoy.txt","w");
        char buf[1024];
        while(!feof(p1))//判斷是不是到了文件結束
        {
                fgets(buf,sizeof(buf),p1);//從文件中讀取
                fputs(buf,p2);//寫入到另一個文件
        }
        fclose(p1);
        fclose(p2);
        return 0;
}




利用一行一行的讀取加密文件

 main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(char *s)
{
	int len = strlen(s);
	while(len--)
		*s++ -= 10;
}

void code(char *s)
{
	int len = strlen(s);
	while(len--)
		*s++ += 10;
}

int main(int argc, char *args[])
{
	FILE *p1 = fopen("main.c","r");
	FILE *p2 = fopen("cpoy1.txt","w");
	FILE *p3 = fopen("cpoy2.txt","w");
	char buf[1024];
	while(!feof(p1))//判斷是不是到了文件結束
	{
		fgets(buf,sizeof(buf),p1);	//從文件中讀取
		code(buf);			//加密這個字符串
		fputs(buf,p2);			//寫入到另一個文件

		decode(buf);			//解密字符串
		fputs(buf,p3);			//寫入到另一個文件

	}
	fclose(p1);//關閉文件
	fclose(p2);
	fclose(p3);
	return 0;
}











chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
chunli@ubuntu:~/pointer$ cat cpoy1.txt 
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*nomyno2mrk|*4}3sx~*vox*G*}~|vox2}3Ersvo2vox7734}55*7G*;:Eysn*myno2mrk|*4}3sx~*vox*G*}~|vox2}3Ersvo2vox7734}55*5G*;:Esx~*wksx2sx~*k|qm6*mrk|*4k|q}eg3PSVO*4z;*G*pyzox2,wksx8m,6,|,3EPSVO*4z<*G*pyzox2,mzy;8~~,6,,3EPSVO*4z=*G*pyzox2,mzy<8~~,6,,3Emrk|*pe;:<>gErsvo2+poyp2z;3399ヴ需耄垰§pqo~}2p6}soyp2p36z;3E99耄 myno2p3E99僵餮滽p~}2p6z<3E99烴諶耄nomyno2p3E99滽p~}2p6z=3E99烴諶耄pmvy}o2z;3E99ン pmvy}o2z<3Epmvy}o2z=3E|o|x*:Echunli@ubuntu:~/pointer$

chunli@ubuntu:~/pointer$ cat cpoy2.txt 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(char *s)
{
	int len = strlen(s);
	while(len--)
		*s++ -= 10;
}

void code(char *s)
{
	int len = strlen(s);
	while(len--)
		*s++ += 10;
}

int main(int argc, char *args[])
{
	FILE *p1 = fopen("main.c","r");
	FILE *p2 = fopen("cpoy1.txt","w");
	FILE *p3 = fopen("cpoy2.txt","w");
	char buf[1024];
	while(!feof(p1))//判斷是不是到了文件結束
	{
		fgets(buf,sizeof(buf),p1);	//從文件中讀取
		code(buf);			//加密這個字符串
		fputs(buf,p2);			//寫入到另一個文件

		decode(buf);			//解密字符串
		fputs(buf,p3);			//寫入到另一個文件

	}
	fclose(p1);//關閉文件
	fclose(p2);
	fclose(p3);
	return 0;
}



從文件格式化讀取

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        char buf[1024];
        sprintf(buf,"%s--%d","1234",5678);//格式化輸出到 -> 字符串數組
        printf("%s\n",buf);

        FILE *p = fopen("hello.txt","w");
        fprintf(p,"%s %d \n",buf,9999);//格式化輸出到文件
        fclose(p);

        FILE *p1 = fopen("hello.txt","r");
        fscanf(p1,"%s\n",buf);//從文件格式化輸入 遇到空格就會停止
        printf("%s \n",buf);

        FILE *p2 = fopen("hello.txt","r");
        fgets(buf,99,p2);//從文件格式化輸入 遇到空格不會停止
        printf("%s",buf);
        fclose(p);

        return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
1234--5678
1234--5678 
1234--5678 9999 

chunli@ubuntu:~/pointer$ cat hello.txt 
1234--5678 9999




文件輸入初步1 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        char buf[1024];
        FILE *p = fopen("hello.txt","w");
        for(int a = 0;a<10;a++)
        {
                sprintf(buf,"%s--%d","1234",a);//格式化輸出到 -> 字符串數組
                fprintf(p,"%s %d \n",buf,a*a);//格式化輸出到文件
        }
        fclose(p);

        return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
chunli@ubuntu:~/pointer$ cat hello.txt 
1234--0 0 
1234--1 1 
1234--2 4 
1234--3 9 
1234--4 16 
1234--5 25 
1234--6 36 
1234--7 49 
1234--8 64 
1234--9 81


獲取鍵盤輸入到文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        char buf[1024];
        FILE *p = fopen("hello.txt","w");
        for(int a = 0;a<3;a++)
        {
                gets(buf);
                fprintf(p,"%s\n",buf);//格式化輸出到文件
        }
        fclose(p);

        return 0;
}


chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
main.c: In function ‘main’:
main.c:10:3: warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
   gets(buf);
   ^
/tmp/ccESW6f6.o: In function `main':
main.c:(.text+0x54): warning: the `gets' function is dangerous and should not be used.
123
1qaz
asdfghj
chunli@ubuntu:~/pointer$ cat hello.txt 
123
1qaz
asdfghj



追加寫入文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
        char buf[1024];
        FILE *p = fopen("hello.txt","a"); //對已有文件追加內容如果文件不存在就創(chuàng)建
        for(int a = 0;a<3;a++)
        {
                gets(buf);
                fprintf(p,"%s\n",buf);//格式化輸出到文件
        }
        fclose(p);

        return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out 
main.c: In function ‘main’:
main.c:10:3: warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
   gets(buf);
   ^
/tmp/cc1C6VG0.o: In function `main':
main.c:(.text+0x54): warning: the `gets' function is dangerous and should not be used.
qwertfg
12345
1qaz
chunli@ubuntu:~/pointer$ cat hello.txt 
123
1qaz
asdfghj
qwertfg
12345
1qaz





linux 系統(tǒng)之間通過網絡傳輸文本文件1一次發(fā)送一個字符

參考我的linux網絡通信

http://990487026.blog.51cto.com/10133282/1773543

替換主函數就可以了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
int main(int argc, char *args[])
{
        if (argc < 3)
        {
                printf("請輸入2個參數 1發(fā)送/2接收需要發(fā)送文件名/接收另存為文件名 \n");
                return 0;
        }

        if (atoi(args[1]) == 1)
        {
                char destined[] = "10.11.12.4";
                FILE *read = fopen(args[2],"r");
                char c = 0;
                while((c = fgetc(read)) != EOF)
                {
                        send_socket(destined, 8080, &c, sizeof(char));
                        //printf("%c",c);
                }
                c = EOF;
                send_socket(destined, 8080, &c, sizeof(char));
        }

        if (atoi(args[1]) == 2)
        {
                FILE *write = fopen(args[2],"w");
                bind_socket(8080);
                char buf[100] = {0};
                char IP[100] = { 0 };
                while(1)
                {

                        recv_socket(buf, 1, IP);
                        if(buf[0] == EOF) break;
                        fprintf(write, "%s", buf);
                }
        }

        return 0;
}
編譯
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

發(fā)送端執(zhí)行
chunli@ubuntu:~/pointer$ ./a.out 1 main.c 

接收端執(zhí)行
chunli@ubuntu:~/pointer$ ./a.out 2 recieve






linux 系統(tǒng)之間通過網絡傳輸文本文件2一次發(fā)送一行字符

參考我的linux網絡通信

http://990487026.blog.51cto.com/10133282/1773543

替換主函數就可以了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
int main(int argc, char *args[])
{
        if (argc < 3)
	{
		printf("請輸入2個參數 1發(fā)送/2接收需要發(fā)送文件名/接收另存為文件名 \n");
		return 0;
	}

	if (atoi(args[1]) == 1)
        {
		char destined[] = "10.11.12.4";
		FILE *read = fopen(args[2],"r");
		char buf[999] = {0};
		while(!feof(read))
		{
			fgets(buf, sizeof(buf), read);//從p1讀取一行
                	send_socket(destined, 8080, buf, strlen(buf));
		}
		buf[0] = EOF;
                send_socket(destined, 8080, buf, sizeof(char));
        }

	if (atoi(args[1]) == 2)
        {
		FILE *write = fopen(args[2],"w");
                bind_socket(8080);
                char buf[999] = {0};
                char IP[100] = {0};
		while(1)
		{
			memset(buf, 0, sizeof(buf));
                	recv_socket(buf, sizeof(buf), IP);
			fprintf(write, "%s", buf);
			if(buf[0] == EOF) 
			{
				break;
			}
		}
        } 

        return 0;
}

編譯
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

接收端運行
chunli@ubuntu:~/pointer$ ./a.out 2 recieve.c

發(fā)送端運行
chunli@ubuntu:~/pointer$ cat send 
tcpdump詳細用法 
 
第一種是關于類型的關鍵字主要包括hostnetport, 例如 host 210.27.48.2指明 210.27.48.2是一臺主機net 202.0.0.0 指明 202.0.0.0是一個網絡地址port 23 指明端口號是23。如果沒有指定類型缺省的類型是host. 
 
第二種是確定傳輸方向的關鍵字主要包括src , dst ,dst or src, dst and src ,這些關鍵字指明了傳輸的方向。舉例說明src 210.27.48.2 ,指明ip包中源地址是210.27.48.2 , dst net 202.0.0.0 指明目的網絡地址是202.0.0.0 。如果沒有指明方向關鍵字則缺省是src or dst關鍵字。 

chunli@ubuntu:~/pointer$ ./a.out 1 send

接收端查看
chunli@ubuntu:~/pointer$ cat recieve
tcpdump詳細用法 
 
第一種是關于類型的關鍵字主要包括hostnetport, 例如 host 210.27.48.2指明 210.27.48.2是一臺主機net 202.0.0.0 指明 202.0.0.0是一個網絡地址port 23 指明端口號是23。如果沒有指定類型缺省的類型是host. 
 
第二種是確定傳輸方向的關鍵字主要包括src , dst ,dst or src, dst and src ,這些關鍵字指明了傳輸的方向。舉例說明src 210.27.48.2 ,指明ip包中源地址是210.27.48.2 , dst net 202.0.0.0 指明目的網絡地址是202.0.0.0 。如果沒有指明方向關鍵字則缺省是src or dst關鍵字。


更高效率。文件發(fā)送

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
#include <sys/stat.h>
int main(int argc, char *args[])
{
        if (argc < 3)
	{
		printf("請輸入2個參數 1發(fā)送/2接收需要發(fā)送文件名/接收另存為文件名 \n");
		return 0;
	}

	if (atoi(args[1]) == 1)
        {
		char destined[] = "10.11.12.4";
		FILE *read = fopen(args[2],"r");
		struct stat st;
		stat(args[2], &st);			//調用stat函數會把文件的相關信息放入結構st當中
		char *buf = (char *)malloc(st.st_size);	//在堆里面根據文件實際大小動態(tài)分配一個數組
		char *log = buf;
		memset(buf, 0, st.st_size);		//把堆當中申請的內存清空
		while(!feof(read))
		{
			char tmp[100] = {0};
			fgets(tmp, sizeof(tmp), read);//從p1讀取一行
			strcat(buf, tmp);
		}
                send_socket(destined, 8080, buf, strlen(buf));
		char c = EOF;
                send_socket(destined, 8080, &c, sizeof(char));
		//free(log);
		//fclose(read);
        }


	if (atoi(args[1]) == 2)
        {
		FILE *write = fopen(args[2],"w");
                bind_socket(8080);
                char buf[999] = {0};
                char IP[100] = {0};
		while(1)
		{
			memset(buf, 0, sizeof(buf));
                	recv_socket(buf, sizeof(buf), IP);
			fprintf(write, "%s", buf);
			if(buf[0] == EOF) 
			{
				break;
			}
		}
        } 

        return 0;
}

編譯
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

chunli@ubuntu:~/pointer$ cat send 
tcpdump詳細用法 
 
 
第二種是確定傳輸方向的關鍵字主要包括src , dst ,dst or src, dst and src


發(fā)送端
chunli@ubuntu:~/pointer$ ./a.out 1 send 

接收端
chunli@ubuntu:~/pointer$ ./a.out 2 recieve


【產生一定數量的隨機數保存到文件再從文件中讀出并排序保存到另外一個文件中】

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int create_rand(int num)
{
	srand((unsigned int)time(NULL));
	FILE *p = fopen("a.txt","w");
	if(p == NULL) return 0;
	for(int i = 0; i< num;i++)
	{
		fprintf(p,"%d \n",rand());
	}
	fclose(p);
	return 0;
}

int  read_arr(int *arr,int len)
{
	FILE *p = fopen("a.txt","r");
	if(p == NULL) return 0;
	int i = 0;
	int value = 0;
	while (!feof(p) && len --)
	{
		fscanf(p,"%d",&value);
		arr[i] =  value;
		i++;
	}
	fclose(p);
	return 0;
}

int  write_arr(int *arr,int len)
{
	FILE *p = fopen("b.txt","w");
	if(p == NULL) return 0;
	for(int i = 0;i<len;i++)
	{
		fprintf(p,"%d\n",arr[i]);
	}
	fclose(p);
	return 0;
}

void printf_arr(int *arr,int len)
{
	for(int i = 0;i<len;i++)
	{
		printf("arr[%d] = %d \n" ,i,arr[i]);
	}
}

void bobble(int *arr,int len)
{
	for(int i = 0;i<len;i++)
	{
		for(int j = 1;j<len-i;j++)
		{
			if(arr[j] < arr[j-1])
			{
				int tmp = arr[j];
				arr[j] = arr[j-1];
				arr[j-1] = tmp;
			}
		}
	}
}

int main()
{
	int arr[9999] = {0}; 
	create_rand(sizeof(arr)/sizeof(int));
	read_arr(arr,sizeof(arr)/sizeof(int));
	printf_arr(arr,sizeof(arr)/sizeof(int));
	bobble(arr,sizeof(arr)/sizeof(int));
	printf("-------------------------------------\n");
	printf_arr(arr,sizeof(arr)/sizeof(int));
	write_arr(arr,sizeof(arr)/sizeof(int));
}

編譯并執(zhí)行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out




fseek函數

ftell函數

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


int main()
{
	char buf[999]={0};
	int num = 0; 
	FILE *p = fopen("text","r");
	if(p == NULL) return 0;

	/*	文件位置設定	*/
	fseek(p,0,SEEK_SET);	//SEEK_SET,設定文件開始位置
	//fseek(p,-6,SEEK_END);//SET_END,從文件末尾向前偏移N個字節(jié)為有效(負數向前移動正數向后移動)
	printf("當前位置%ld \n",ftell(p));


	while(!feof(p))
	{
		memset(buf,0,sizeof(buf));
		//fseek(p,3,SEEK_CUR);//在當前位置向后偏移N個字節(jié)
		fgets(buf,sizeof(buf),p);
		printf("當前位置%ld\t%s",ftell(p),buf);
	}
}



編譯運行
chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
當前位置0 
當前位置8	abcdefg
當前位置21	Hello World!
當前位置45	Welcome to chunli home!
當前位置68	歡迎學習C語言
當前位置75	123456
當前位置103	此行下面有一個空行
當前位置104	
當前位置104	chunli@ubuntu:~/file$




fprintf()是臨時寫到內存中的

fflush函數


將數據實時寫入磁盤 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


int main()
{
        char buf[20]={0};
        int num = 0;
        FILE *p = fopen("text","w");
        if(p == NULL) return 0;
        while(1)
        {
                memset(buf,0,sizeof(buf));
                scanf("%s",buf);
                if(strncmp(buf,"exit",4) == 0) {break;} //當輸入的字符是exit就退出
                fprintf(p,"%s \n",buf);                 //將數據寫入臨時內存
                fflush(p);                              //將本次的數據從內存同步到磁盤(效率極低) 
        }       
        fclose(p);//此時才將數據從內存寫入到磁盤
        return 0;
}
chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
12342141

exit


fwrite寫二進制文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        FILE *p = fopen("text.dat","wb");
        if(p == NULL) return 0;
        char buf[100] = {"1111\r\n1111\r\n2222\r\n3333"};
        //fwrite(buf,1,strlen(buf),p);//這兩種方式是一樣的
        fwrite(buf,strlen(buf),1,p);//一次寫strlen的長度寫1次
        fclose(p);
        return 0;
}


文件二進制加密解密
chunli@ubuntu:~/file$ cat main.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CODE 0x1234
int main()
{
	//文件加密哈
	{
		FILE *p1 = fopen("main.c","rb");
		if(p1 == NULL) return 0;
	
		FILE *p2 = fopen("1加密.dat","wb");
		if(p2 == NULL) return 0;
	
		while(!feof(p1))
		{
			char buf[999] = {0};
			fgets(buf,sizeof(buf),p1);// 讀一行字符串
			size_t len = strlen(buf);
			for(int i = 0;i<len;i++)//處理每個字符串
			{
				int tmp = buf[i] ^ CODE ;//加密并轉換為int
				fwrite(&tmp,sizeof(int),1,p2);//寫入文件
			}
		}
		fclose(p1);
		fclose(p2);
	}
	//文件解密
	{
		FILE *p1 = fopen("1加密.dat","rb");
		if(p1 == NULL) return 0;
	
		int tmp = 0 ;
		FILE *p2 = fopen("2解密.dat","wb");
		if(p2 == NULL) return 0;
	
		while(fread(&tmp,sizeof(int),1,p1)) //此處不能用feof判斷
		{
			char c = tmp ^ CODE;         //將讀取的int解密轉換為char
			fwrite(&c,sizeof(char),1,p2);
		}
		fclose(p1);
		fclose(p2);
	}	

	return 0;
}


chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
chunli@ubuntu:~/file$ ll
total 24K
-rw-rw-r-- 1 chunli chunli 3.9K May 31 16:27 1加密.dat
-rw-rw-r-- 1 chunli chunli  973 May 31 16:27 2解密.dat
-rwxrwxr-x 1 chunli chunli 8.8K May 31 16:27 a.out
-rw-rw-r-- 1 chunli chunli  973 May 31 16:28 main.c



二進制文件復制

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
int main(int argc,char *args[])
{
	if(argc < 3)
	{
		printf("參數不夠 \n");
		return 0;
	}

	FILE *p1 = fopen(args[1],"rb");
	if(p1 == NULL) 
	{
		printf("打開文件%s失敗\n",args[1]);
		return 0;
	}

	FILE *p2 = fopen(args[2],"wb");
	if(p2 == NULL)
	{
		printf("打開文件%s失敗\n",args[2]);
		return 0;
	}
	/*		方式一		*/
	char buf[10] = {0};			//設定緩存區(qū)大小
	while(!feof(p1)) //此處不能用feof判斷
	{
		size_t size = fread(buf,1,sizeof(buf),p1);
		//printf("%ld \n",size);		//查看本次讀取了多少個有效字節(jié)
		fwrite(buf,1,size,p2);		//寫入有效個字節(jié)
	}
	/*		方式二  最高效
	struct stat st;
	stat(args[1],&st);
	char *buf = malloc(st.st_size);
	fread(buf,st.st_size,1,p1);
	fwrite(buf,st.st_size,1,p2);
	free(buf);
	*/

	fclose(p1);
	fclose(p2);

	return 0;
}


chunli@ubuntu:~/file$ gcc -std=c99 -o mycp main.c && ./mycp /sbin/ifconfig  ./ifconfig_copy 
chunli@ubuntu:~/file$ chmod +x ifconfig_copy 
chunli@ubuntu:~/file$ ./ifconfig_copy 
eth0      Link encap:Ethernet  HWaddr 00:0c:29:ed:22:c1  
          inet addr:10.11.12.4  Bcast:10.11.12.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:feed:22c1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:85812 errors:0 dropped:14 overruns:0 frame:0
          TX packets:55751 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:15630825 (15.6 MB)  TX bytes:26146882 (26.1 MB)

	


結構體與文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student 
{
	int ID;
	char name[100];
};
int main()
{
//		把結構體寫入文件
	{
		struct student st[] ={
					{0,"劉德華0"},
					{1,"劉德華1"},
					{2,"劉德華2"},
					{3,"劉德華3"},
					{4,"劉德華4"},
					{5,"劉德華5"},
					{6,"劉德華6"},
					{7,"劉德華7"},
					{8,"劉德華8"},
					{9,"劉德華9"},
		};
		FILE *p = fopen("data","wb");
		if(p == NULL)
		{
			printf("創(chuàng)建data文件失敗\n");
			return 0;
		}
		fwrite(st,sizeof(struct student),10,p);
		fclose(p);
	}
//		修改結構體文件
	{
		struct student st = {45,"周杰倫"};
		FILE *p = fopen("data","rb+");
		if(p == NULL)
		{
			printf("打開文件data失敗\n");
			return 0;
		}	
		fseek(p,sizeof(st)*2,SEEK_SET);//將第3個位置的信息修改為st
		fwrite(&st,sizeof(st),1,p);
		fclose(p);
	}
//		從文件中讀出結構體
	{
		FILE *p = fopen("data","rb");
		if(p == NULL)
		{
			printf("打開文件data失敗\n");
			return 0;
		}
		struct student st;
		memset(&st,0,sizeof(st));
		while(fread(&st,sizeof(st),1,p))
		{
			printf("Id=%u,name=%s\n",st.ID,st.name);
		}
		fclose(p);


	}


	return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
Id=0,name=劉德華0
Id=1,name=劉德華1
Id=45,name=周杰倫
Id=3,name=劉德華3
Id=4,name=劉德華4
Id=5,name=劉德華5
Id=6,name=劉德華6
Id=7,name=劉德華7
Id=8,name=劉德華8
Id=9,name=劉德華9



從結構體文件中讀出指定的數據并返回耗時

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>  
struct student 
{
	int ID;
	char name[100];
};

int main()
{
//		把結構體寫入文件
	{
		struct student st[] ={
					{0,"劉德華0"},
					{1,"劉德華1"},
					{2,"劉德華2"},
					{3,"劉德華3"},
					{4,"劉德華4"},
					{5,"劉德華5"},
					{6,"劉德華6"},
					{7,"劉德華7"},
					{8,"劉德華8"},
					{9,"劉德華9"},
		};
		FILE *p = fopen("data","wb");
		if(p == NULL)
		{
			printf("創(chuàng)建data文件失敗\n");
			return 0;
		}
		fwrite(st,sizeof(struct student),10,p);
		fclose(p);
	}
//		從文件中讀出結構體
	{
		FILE *p = fopen("data","rb");
		if(p == NULL)
		{
			printf("打開文件data失敗\n");
			return 0;
		}
		struct student st;
		unsigned int ID = 0;
		clock_t ct ;
		while(1)
		{
			memset(&st,0,sizeof(st));
			printf("請輸入ID: ");
			scanf("%u",&ID);
			if(ID == 0) {break;}
			ct = clock();
			fseek(p,sizeof(st)*(ID-1),SEEK_SET);
			fread(&st,sizeof(st),1,p);
			ct = clock() - ct;
			printf("ms = %ld,Id=%u,name=%s\n",ct,st.ID,st.name);
		}
		fclose(p);


	}


	return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
請輸入ID: 1
ms = 40,Id=0,name=劉德華0
請輸入ID: 1
ms = 9,Id=0,name=劉德華0
請輸入ID: 9
ms = 9,Id=8,name=劉德華8
請輸入ID: 4
ms = 9,Id=3,name=劉德華3




結構體數組信息保存到二進制文件從二進制文件讀出在結構體數組中插入一條記錄保存到文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>  

struct student 
{
	int ID;
	char name[100];
};

void insert(struct student *p,int len)
{
      for(int i = len-1;i>=2;i--)
      {
      	p[i+1] = p[i];
      }
}

int main()
{
//		把結構體寫入文件
	{
		struct student st[] ={
					{0,"劉德華"},
					{1,"宏碁"},
					{2,"戴爾"},
					{3,"華為"},
					{4,"阿里巴巴"},
					{5,"51CTO"},
					{6,"清華大學"},
					{7,"貝爾實驗室"},
					{8,"阿基米德"},
					{9,"C/C++"},
					{11,"六一兒童節(jié)"},
		};
		FILE *p = fopen("data","wb");
		if(p == NULL)
		{
			printf("創(chuàng)建data文件失敗\n");
			return 0;
		}
		fwrite(st,sizeof(struct student),sizeof(st)/sizeof(struct student),p);
		fclose(p);
	}
//		從文件中讀出結構體
	{
		FILE *p = fopen("data","rb");
		if(p == NULL)
		{
			printf("打開文件data失敗\n");
			return 0;
		}
		struct student *pst = calloc(100,sizeof(struct student)); //在內存的動態(tài)存儲區(qū)中分配n個長度為size的連續(xù)空間函數返回一個指向分配起始地址的指針
		int index = 0;
		while(fread(&pst[index],sizeof(struct student),1,p))//一直讀
		{
			printf("讀文件%d-> Id=%u,name=%s\n",index,pst[index].ID,pst[index].name);
			index++;
		}
		fclose(p);

//		在這個結構體中插入數據
		insert(pst,index);//此時從序號為2的結構體index都向后移動了以為
		pst[2].ID = 12;		//為新的結構體賦值
		strcpy(pst[2].name,"Windows 怎么樣");

//		遍歷這個結構體
		for(int i = 0;i < index + 1;i++)
		{
			printf("遍歷結構體%d -> ID = %u,name=%s \n",i,pst[i].ID,pst[i].name);
		}
//將修改的結果保存到文件		
		{
			FILE *p = fopen("data","wb");
			if(p == NULL)
			{
				printf("創(chuàng)建文件失敗\n");
				return 0;
			}
			fwrite(&pst,sizeof(struct student),index+1,p);
			fclose(p);
		}


	}


	return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
讀文件0-> Id=0,name=劉德華
讀文件1-> Id=1,name=宏碁
讀文件2-> Id=2,name=戴爾
讀文件3-> Id=3,name=華為
讀文件4-> Id=4,name=阿里巴巴
讀文件5-> Id=5,name=51CTO
讀文件6-> Id=6,name=清華大學
讀文件7-> Id=7,name=貝爾實驗室
讀文件8-> Id=8,name=阿基米德
讀文件9-> Id=9,name=C/C++
讀文件10-> Id=11,name=六一兒童節(jié)
遍歷結構體0 -> ID = 0,name=劉德華 
遍歷結構體1 -> ID = 1,name=宏碁 
遍歷結構體2 -> ID = 12,name=Windows 怎么樣 
遍歷結構體3 -> ID = 2,name=戴爾 
遍歷結構體4 -> ID = 3,name=華為 
遍歷結構體5 -> ID = 4,name=阿里巴巴 
遍歷結構體6 -> ID = 5,name=51CTO 
遍歷結構體7 -> ID = 6,name=清華大學 
遍歷結構體8 -> ID = 7,name=貝爾實驗室 
遍歷結構體9 -> ID = 8,name=阿基米德 
遍歷結構體10 -> ID = 9,name=C/C++ 
遍歷結構體11 -> ID = 11,name=六一兒童節(jié)




我有一份學生名單文件需要為每個學生隨機ID值存儲到文件再讀出來按照ID順序打印到屏幕

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct student
{
	unsigned int ID;
	char name[20];
};

void create_num(int arr[],int len)//將傳過來的數組裝入亂序隨機值
{
	int i = 0;
	int j = 0;
	srand((unsigned int)time(NULL));
	while(i<len)
	{
		int tmp = rand() % len;
		for(j = 0;j<i;j++)
		{
			if(arr[j] == tmp)
				{
					break;
				}
		}
		if(j == i)
		{
			arr[i] = tmp;
			i++;
		}
	}
}

int main()
{
////////	從文件中讀取信息修改存儲到文件		///////////////////////////////////////////////
	{	
		srand((unsigned int)time(NULL));
		FILE *p  = fopen("student","r");
		if(p == NULL ) {return 0;}
		FILE *p2 = fopen("data","wb");
		if(p2 == NULL ) {return 0;}
		struct student st = {0,""};
		char buf[100] = {0};
		int arr[100];				//定義一個數組
		create_num(arr,sizeof(arr)/sizeof(int));//為數組載入n個亂序不重復個數值
		int index = 0;
		while(!feof(p))
		{
			fgets(st.name,sizeof(st.name),p);
			int len = strlen(st.name);
			if(st.name[len-1] == '\n'){st.name[len-1] = 0;}//去除每一行的'\n'字符
			st.ID = arr[index++];		//把數組的亂序不重復值拿出來
			//printf("%d,%s \n",st.ID,st.name);
			fwrite(&st,sizeof(st),1,p2);
		}
		fclose(p);
		fclose(p2);
	}	
////////	從文件中讀取	////////////////////////////////////////////////
	{
		FILE *p = fopen("data","rb"); 
		if(p == NULL) {return 0;}
		struct student st[100];
		struct student tmp;
		int index = 0;
		while( fread(&st[index++],sizeof(struct student),1,p));//將文件讀取到內存
	/////////	將結構體按照ID排序一下 		//////////////////////////////////////////////////	
		for(int i=1;i<index-1;i++)
		{
			for(int j =1;j<index-i-1;j++)
			{
				if(st[j].ID < st[j-1].ID)
				{
					tmp    = st[j];
					st[j]  = st[j-1];
					st[j-1]= tmp;
				}
			}
		}
	////////////	遍歷輸出結構體信息	//////////////////////////////////////////
		for(int i = 0;i<index -2;i++)
		{
			printf("%d,%s \n",st[i].ID,st[i].name);
		}
	}   
	return  0;
}
學生姓名為文件
chunli@ubuntu:~/file$ cat student 
張三豐
李小龍
樸槿惠
聯想
戴爾
孫悟空
收音機
銀河系
西瓜

編譯執(zhí)行
chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
16,戴爾 
23,聯想 
41,孫悟空 
55,西瓜 
58,收音機 
71,銀河系 
74,張三豐 
84,李小龍 
97,樸槿惠






向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI