C语言相关文件操作

1.对已知文件进行分割。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <stdlib.h>

 4 FILE *in,*out;

 5 char filename[256],ch,cfilename[256];

 6 void depart()

 7 {

 8  char ext[6][6]={

 9  "a.txt",

10  "b.txt",

11  "c.txt",

12  "d.txt",

13  "e.txt",

14  "f.txt"};

15  unsigned long int n=1,k,byte=0;

16  unsigned int j=0,i=0;

17  printf("input filename:\n");

18  scanf("%s",filename);

19  strcpy(cfilename,filename);

20  if((in=fopen(filename,"r")) == NULL)

21  {

22   exit(0);

23  }

24  printf("file size:\n");

25  scanf("%d",&n);

26  n = n*1024;

27  while(filename[j] != '.')

28  {

29   j++;

30  }

31  filename[j] = '\0';

32  if((out=fopen(strcat(filename,ext[i]),"w")) == NULL)

33  {

34   exit(0);

35  }

36  

37  fseek(in,0,2);

38  k = ftell(in);

39  fseek(in,0,0);

40  while(k>0)

41  {

42   ch = fgetc(in);

43   fputc(ch,out);

44   byte++;

45   k--;

46   if(byte == n)

47   {

48    fclose(out);

49    byte = 0;

50    strcpy(filename,cfilename);

51    while(filename[j] != '.')

52    {

53     j++;

54    }

55    filename[j]='\0';

56    i++;

57    if((out=fopen(strcat(filename,ext[i]),"w")) == NULL)

58    {

59     exit(0);

60    }

61   }

62  }

63  

64  fclose(in);

65  printf("depart success!\n");

66 }

67 int main()

68 {

69  depart();

70  return 0;

71 }

2.操作临时文件,新建文件(tcc编译器)

 1 #include <stdio.h>

 2 #include <io.h>

 3 int main()

 4 {

 5  /*临时文件的使用方法*/

 6  FILE *temp;

 7  char c;

 8  if((temp=tmpfile()) != NULL)

 9  {

10   fputs("\nhello\nworld",temp);

11  }

12  rewind(temp);//文件指针返回文件头

13  while((c = fgetc(temp)) != EOF)

14  {

15   printf("%c",c);

16  }

17  fclose(temp);

18  /*新建文件的方法*/

19  int handle;

20  char filename[256];

21  printf("input filename:\n");

22  scanf("%s",filename);

23  if((handle = creat(filename,0)) == -1)

24  {//tcc中io.h文件中的creat函数,新建文件。

25   printf("error!");

26  }

27  else

28  {

29   printf("Success");

30   close(handle);

31  }

32 }

本文就写这几个功能,其他再续……

你可能感兴趣的:(文件操作)