I need to write two functions, one to read a file with the first line containing
ID: 3620300 • Letter: I
Question
I need to write two functions, one to read a file with the first line containing the number of integers to be sorted, and the rest the actual desired integers. The second function will take the array returned by Load_File and write it to an output file.long *Load_File (char *Filename, int *Size)
The file contains N+1 integers, one in each line. The first line of the file indicates the number of integers to be sorted, i.e., "N". *Size should be assigned the value of N at the end of the routine. The subsequent lines contain (long) integers.
My Load function is already working.
----
The following is what I have for Save_File -- it doesn't copy all variables of Load function to the output file though.. ---- int Save_File (char *Filename, long *Array, int Size)
The function saves Array to an external file specified by Filename. The output file should have the same format as the input file.
int Save_File(char *Filename, long *Array, int Size) { FILE *fp = fopen(Filename, "w"); int count; if (fp == NULL) { // check to see if file opens; if NULL, failed printf("Error opening file. "); return 0; }
for (count = 0; count < &Size; count++) { fprintf(fp, "%ld ", Array[count]); } fclose(fp); return (sizeof(Array)); }
Thank you!
The following is what I have for Save_File -- it doesn't copy all variables of Load function to the output file though.. ---- int Save_File(char *Filename, long *Array, int Size) { FILE *fp = fopen(Filename, "w"); int count; if (fp == NULL) { // check to see if file opens; if NULL, failed printf("Error opening file. "); return 0; }
for (count = 0; count < &Size; count++) { fprintf(fp, "%ld ", Array[count]); } fclose(fp); return (sizeof(Array)); } int Save_File(char *Filename, long *Array, int Size) { FILE *fp = fopen(Filename, "w"); int count; if (fp == NULL) { // check to see if file opens; if NULL, failed printf("Error opening file. "); return 0; }
for (count = 0; count < &Size; count++) { fprintf(fp, "%ld ", Array[count]); } fclose(fp); return (sizeof(Array)); }
Thank you!
Explanation / Answer
long *Load_file(char *Filename, into size)
{
FILE *fp1, *fp2, *fopen();
int c ;
char
fp1 = fopen( Filename, "r" ); /* open for reading */
if ( fp1 == NULL ) /* check does file exist etc */
{
printf("Cannot open prog.c for reading " );
exit(1); /* terminate program */
}
else if ( fp2 == NULL )
{
printf("Cannot open prog.old for writing ");
exit(1); /* terminate program */
}
else /* both files O.K. */
{
c = getc(fp1) ;
long array[c];
int i=0;
while ( i<c)
{
array[i] = getc( fp1 ) ;
i++;
}
int sz=Save_File("output",array,c);
fp2 = fopen( "Output.txt", "w" ) ;
/* open for writing */
int x=fseek(fp2,0,SEEK_END);
c = getc(fp1)
while ( c != EOF)
{
putc( c, fp2);
c = getc( fp1 ) ;
}
fclose ( fp1 ); /* Now close files */
fclose ( fp2 );
}
return i-1;
}