Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

writting an array to a text file

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How do i write an array of, for example, 30 integer values to a text file? I need to print these values to a file for storage purposes so they can be referred to in the future. Once they have been written to the file I will empty it and calculate another set of values and store them. This process repeats for about 20 iterations.

Thanks
John
 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define DUMP_FILE &quot;C:\\ArrayDump.txt&quot;
#define DUMP_COUNT 20
#define MAX_ELEMS 30
#define MAX_RAND 100

void RandArray( int*,int );
void DisplayArray( int*,int );
int DumpArray( int*,int,char* );
char *ReturnCurrentTime();

int main( void )
{
int iStorage[MAX_ELEMS];
int i;

for( i=0;i<DUMP_COUNT;i++ )
{
RandArray( iStorage,MAX_ELEMS );
DumpArray( iStorage,MAX_ELEMS,DUMP_FILE );
}
printf( &quot;%s has been created...\n&quot;,DUMP_FILE );
return 0;
}

void RandArray( int* array,int iSize )
{
int *p;
time_t t;
srand( time( &t ) );

for( p=array;p<&array[iSize];p++ )
*p=( rand()%MAX_RAND+1 );
}

void DisplayArray( int* array,int iSize )
{
int *p;
for( p=array;p<&array[iSize];p++ )
printf( &quot;%d\n&quot;,*p );
}

int DumpArray( int* array,int iSize,char* sFile )
{
FILE* outFile;
int *p;

outFile=fopen( sFile,&quot;a+&quot; );
if( !outFile )
{
printf( &quot;Error: file cannot be opened\n&quot; );
return 0;
}

fprintf( outFile,&quot;%s&quot;,ReturnCurrentTime() );
for( p=array;p<&array[iSize];p++ )
fprintf( outFile,&quot;%d\n&quot;,*p );

fclose( outFile );
return 1;
}

char *ReturnCurrentTime()
{
time_t timeStarted;
time( &timeStarted );
return asctime( localtime( &timeStarted ) );
}

//The following code just loads an array with random
//integers. The arrays contents are then dumped into
//a text file. This process will loop 20 times. For each
//loop in main(), the random integers will be appended
//into the text file. Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top