一个程序,使用循环从文件中读取可变长度数组

时间:2013-11-07 23:59:11

标签: c

void printArray(char * array, FILE * fp1, int MAX_CHAR)
{ 
 int i; /* initializing i */
 FILE *fp1
 fp1 = fopen("Array.txt","r+");      /* open the file in append mode */
 for (i=0; i<MAX_CHAR; i++)           /* using for loop */
      fprintf(fp1,"%c",*(array+i)); /* writing the array */ 
 fclose(fp1);                       /* close the file pointer */ 

 return 0; 
}

我是C的新手可以有人让我知道我是否正确地做了

1 个答案:

答案 0 :(得分:0)

你在这个功能中遇到了一些错误。以下是我的建议:

void printArray(char *array, const int MAX_CHAR)
{ 
    FILE *fp1;
    fp1 = fopen("Array.txt", "a");      /* open the file in append mode */
    for (int i=0; i<MAX_CHAR; i++)           /* using for loop */
       fprintf(fp1,"%c",*(array+i)); /* writing the array */ 
    fclose(fp1);                       /* close the file pointer */ 
}

关于打开文件时的模式:fopen function。如果您确实想要将fp1作为输入参数传递,请执行以下操作:

void printArray(char *array, FILE *fp1, const int MAX_CHAR)
{ 
    fp1 = fopen("Array.txt", "a");      /* open the file in append mode */
    for (int i=0; i<MAX_CHAR; i++)           /* using for loop */
       fprintf(fp1,"%c",*(array+i)); /* writing the array */ 
    fclose(fp1);                       /* close the file pointer */ 
}

最后,我建议你看看fwrite function