GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 01-Feb-2005, 14:59
robin robin is offline
New Member
 
Join Date: Feb 2005
Posts: 3
robin is on a distinguished road

multiple file creation with fopen?


Hello,

I'm trying to create several files (well actually 64 files) with incrementally with fopen. So, there will be result1 to result64.
Is it possible to do it? Somehow, my program just got a funny char after the "result" file. I know one way to do it is to pass 64 arg to the file.

Any suggestion would be appreciated.

The program:

CPP / C++ / C Code:
#include <stdio.h>

FILE *result;
FILE *stat;


char file_result[]="result";
char file_stat[]="stat";

int main()
{
     int i, src_id;
          
     for (i=1; i<65; i++)
         {
            src_id=0;
            src_id++;
            printf("\n srcid: %d\n", src_id);

            printf("\n open file_result (before): %s\n", file_real); // just for testing
            file_real[6]=src_id;
            printf("\n open file_result (after): %s\n", file_real); //just for testing


            result = fopen(file_result, "w");	
            if ((result = fopen(file_result, "w")) == NULL)
               {
               puts("\nUnable to open the result file\n");
               return 0;
               }
            stat = fopen(file_stat, "w");
            if ((result = fopen(file_stat, "w")) == NULL)
               {
               puts("\nUnable to open the stat file\n");
               return 0;
               }
          }
}
Last edited by LuciWiz : 01-Feb-2005 at 15:16. Reason: Please insert your C code between [c] & [/c] tags
  #2  
Old 01-Feb-2005, 15:15
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,642
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by robin
Hello,

I'm trying to create several files (well actually 64 files) with incrementally with fopen. So, there will be result1 to result64.
Is it possible to do it? Somehow, my program just got a funny char after the "result" file. I know one way to do it is to pass 64 arg to the file.


You could try something like this to generate the file names:

CPP / C++ / C Code:
#include <stdio.h>

int main()
{
  int i;
  char filename[10]; /* space for "result" + 2 digits + zero terminator */
    
  for (i = 1; i < 65; i++) {
    sprintf(filename, "result%d", i);
    printf("i = %d: filename: <%s>\n", i, filename);
  }

  return 0;
}

Here are some of the problems with your method (other than the typographical errors where you used "file_real" instead of "file_result" in a couple of places):

CPP / C++ / C Code:
char file_result[]="result";
This declares that file_result is an array that will hold a total of 7 chars.
It initializes the contents to:

Quote:
result[0] = 'r' (114 decimal)
result[1] = 'e' (101 decimal)
result[2] = 's' (115 decimal)
result[3] = 'u' (117 decimal)
result[4] = 'l' (108 decimal)
result[5] = 't' (116 decimal)
result[6] = 0 (0 decimal)

Now, as you go through the loop, you replace result[6] with integer values from 1 throgh 64.

Problems:
1. Many of these are not printing characters (a security feature?, since you can't easily discover their real name from the command line).

2. String functions (including printf() with %s format specifiers) need to have a sequence of chars terminated by a byte whose value is zero.

The example that I gave lets you use the sprintf() function to convert the decimal numbers to their ascii (printable) digit representations: '1', '2', etc.

Note that the length of the file name string can be as long as 8 characters, so the array must have length of at least 9 chars (to hold the terminating zero as well as the printable characters). I made it 10, just in case we ever want to have file names up to "result999".

Regards,

Dave
  #3  
Old 02-Feb-2005, 04:43
robin robin is offline
New Member
 
Join Date: Feb 2005
Posts: 3
robin is on a distinguished road
That was quick. It fixed the problem.
Thank you very much Dave!

Regards,
  #4  
Old 02-Feb-2005, 06:11
robin robin is offline
New Member
 
Join Date: Feb 2005
Posts: 3
robin is on a distinguished road
Question:
Is there any limit that fopen can create files in MS DOS?
I know that in one MS DOS directory you can only have 512 files.
Any ideas why my program stop creating files after 445 files [(64x7) - 3]?

Thank you.
  #5  
Old 02-Feb-2005, 07:27
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,642
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by robin
Question:
Is there any limit that fopen can create files in MS DOS?
I know that in one MS DOS directory you can only have 512 files.
Any ideas why my program stop creating files after 445 files [(64x7) - 3]?

Thank you.

I don't know (and don't have any way to run any tests).

Sorry.

Regards,

Dave
  #6  
Old 14-Aug-2006, 08:34
ifa ifa is offline
New Member
 
Join Date: Aug 2006
Posts: 1
ifa is on a distinguished road

Re: multiple file creation with fopen?


Quote:
Originally Posted by davekw7x
You could try something like this to generate the file names:

CPP / C++ / C Code:
#include <stdio.h>

int main()
{
  int i;
  char filename[10]; /* space for "result" + 2 digits + zero terminator */
    
  for (i = 1; i < 65; i++) {
    sprintf(filename, "result%d", i);
    printf("i = %d: filename: <%s>\n", i, filename);
  }

  return 0;
}

Here are some of the problems with your method (other than the typographical errors where you used "file_real" instead of "file_result" in a couple of places):

CPP / C++ / C Code:
char file_result[]="result";
This declares that file_result is an array that will hold a total of 7 chars.
It initializes the contents to:



Now, as you go through the loop, you replace result[6] with integer values from 1 throgh 64.

Problems:
1. Many of these are not printing characters (a security feature?, since you can't easily discover their real name from the command line).

2. String functions (including printf() with %s format specifiers) need to have a sequence of chars terminated by a byte whose value is zero.

The example that I gave lets you use the sprintf() function to convert the decimal numbers to their ascii (printable) digit representations: '1', '2', etc.

Note that the length of the file name string can be as long as 8 characters, so the array must have length of at least 9 chars (to hold the terminating zero as well as the printable characters). I made it 10, just in case we ever want to have file names up to "result999".

Regards,

Dave
Hi dave,
I've tried the code in my program, but failed to do so.
Appreciate if you could help me figure-out the problem in my code.
Below are the details:
1. I'm trying to open several files named desc1.txt, desc2.txt, ... descn.txt using fopen.
2. Perform tokenization on the contents.
3. Save the tokenized words in the new files named tokword1.txt, tokword2.txt,... tokwordn.txt.
CPP / C++ / C Code:
/* string token from file */

#include <stdio.h> /* standard input-output library */
#include <string.h> /* string library */

void main()
{
FILE *inputptr; 
FILE *outputptr;
char filein[7];
char fileout[10];
char content[1000]; /* declare 1000 space/array for description */
char *tknword[50]; /* declare 50 space/arrays/lines for tokenized word */
char *tokptr;
int i;
int j;

for(i=1;i<5;i++)
{
	sprintf(filein,"desc%d.txt",i);
	sprintf(fileout,"tokword%d.txt",i);

	inputptr = fopen(filein, "r"); /* open input file to read */
	outputptr = fopen(fileout, "w+"); /* open output file to read and write */

	if((outputptr=fopen(fileout,"w+"))==NULL)
		printf("file cannot be openned");

	fgets(content,1000,inputptr); /* read char by char from input file*/

	tokptr=strtok(content," ");

	for(j=1;tokptr!=NULL;j++) /* token and put words line by line */
	{
		{
			tknword[j]=tokptr;
			fprintf(outputptr,"%s\n",tknword[j]);
		}

		tokptr=strtok(NULL," ,."); /* token by space, comma, full stop */
	}

	fclose(inputptr); /* close file */
	fclose(outputptr);
	}
}

I've managed to perform the process using one single file, but failed when involved multiple files.
Please help me.

---
Ifa
Last edited by cable_guy_67 : 14-Aug-2006 at 08:47. Reason: Please surround your C code with [cpp] ... [/cpp]
  #7  
Old 16-Aug-2006, 23:38
davis
 
Posts: n/a

Re: multiple file creation with fopen?


Quote:
Originally Posted by robin
Question:
Is there any limit that fopen can create files in MS DOS?
I know that in one MS DOS directory you can only have 512 files.
Any ideas why my program stop creating files after 445 files [(64x7) - 3]?

Thank you.

After using fopen, are you using fclose on the FILE*? In DOS, there is a perscribed number of file handles available to the shell. You can modify this by increasing the FILES=nnn in your CONFIG.SYS file. If you are running a "DOS session" from something like Windows, then you need to modify your DOS emulation environment appropriately.

I don't know how you're going about writing your code, but I thought that I'd offer a quick hack for you to review as something to consider.

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define MAX_FILES 64

int openArrayFile( FILE** pFilesArray, const int index, const char* fileName, const char* openMode )
{
    char* pHelloWorld = "Hello, World!\n";
    int rc = (index >= MAX_FILES ) ? -1 : 0;
    if( !rc )
    {
	pFilesArray[index] = fopen( fileName, openMode );
	if( !pFilesArray[index] )
	{
	    rc = errno;
	}
	fwrite( pHelloWorld, strlen( pHelloWorld ), 1, pFilesArray[index] );
    }
    return rc;
}

int closeArrayFile( FILE** pFilesArray, const int index )
{
    int rc = (index >= MAX_FILES ) ? -1 : 0;
    if( !rc )
    {
	if( !pFilesArray[index] )
	{
	    rc = ERANGE;
	}
	else
	{
	    rc = fclose( pFilesArray[index] );
	    if( rc )
	    {
		rc = errno;
	    }
	    else
	    {
		pFilesArray[index] = 0;
	    }
	}
    }
    return rc;
}

int main()
{
    int rc = 0;
    int i = 0;
    char filenameBase[16] = {0};
    FILE** pFilesArray = (FILE**)calloc( sizeof( FILE*), MAX_FILES );
    if( pFilesArray != NULL )
    {
        for( i = 1; i < 1+ MAX_FILES; i++ )
        {
        	if( i > 999 )
        	{
        	    rc = ERANGE;
        	    break;
        	}
        	else if( i < 10 )
        	{
        	    sprintf( filenameBase, "result00%d", i );
        	}
        	else if( i < 100 )
        	{
        	    sprintf( filenameBase, "result0%d", i );
        	}
        	else
        	{
        	    sprintf( filenameBase, "result%d", i );
        	}
        	rc = openArrayFile( pFilesArray, -1 + i, filenameBase, "w" );
        	if( rc )
        	{
        	    break;
        	}
        	else
        	{
        	    rc = closeArrayFile( pFilesArray, -1 + i );
        	    if( rc )
        	    {
        		break;
        	    }
        	}
        }
        free( pFilesArray );
    }
    else
    {
        rc = errno;
    }
    return rc;
}


Output:

Code:
$ ls result* result001 result007 result013 result019 result025 result031 result037 result043 result049 result055 result061 result002 result008 result014 result020 result026 result032 result038 result044 result050 result056 result062 result003 result009 result015 result021 result027 result033 result039 result045 result051 result057 result063 result004 result010 result016 result022 result028 result034 result040 result046 result052 result058 result064 result005 result011 result017 result023 result029 result035 result041 result047 result053 result059 result006 result012 result018 result024 result030 result036 result042 result048 result054 result060 $ cat result* Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! // valgrind results ==3515== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 1) --3515-- --3515-- supp: 12 Ubuntu-stripped-ld.so ==3515== malloc/free: in use at exit: 0 bytes in 0 blocks. ==3515== malloc/free: 65 allocs, 65 frees, 22,784 bytes allocated. ==3515== ==3515== All heap blocks were freed -- no leaks are possible. --3515-- memcheck: sanity checks: 1 cheap, 1 expensive --3515-- memcheck: auxmaps: 0 auxmap entries (0k, 0M) in use --3515-- memcheck: auxmaps: 0 searches, 0 comparisons --3515-- memcheck: secondaries: 10 issued (640k, 0M) --3515-- memcheck: secondaries: 17 accessible and distinguished (1088k, 1M) --3515-- tt/tc: 3,613 tt lookups requiring 3,654 probes --3515-- tt/tc: 3,613 fast-cache updates, 3 flushes --3515-- translate: new 1,714 (36,737 -> 593,768; ratio 161:10) [0 scs] --3515-- translate: dumped 0 (0 -> ??) --3515-- translate: discarded 5 (119 -> ??) --3515-- scheduler: 51,354 jumps (bb entries). --3515-- scheduler: 1/2,450 major/minor sched events. --3515-- sanity: 2 cheap, 1 expensive checks. --3515-- exectx: 30,011 lists, 12 contexts (avg 0 per list) --3515-- exectx: 142 searches, 130 full compares (915 per 1000) --3515-- exectx: 0 cmp2, 37 cmp4, 0 cmpAll

Note that I appended some zeros in front of the resultNNN so that they would list better. The reason that I created the array of file pointers is so that someone could later access them and write to them (other than Hello, World!) and free them without fear. Obviously, one can easily create two file pointer arrays for the input (to strtok) and the output (tokens) as per ifa's comments. It would then be very easy to write a tokenizing routine that tosses the tokens found in the input file into the output file. The signature of such a function would look something like:

CPP / C++ / C Code:
int tokenInputOutput( FILE** pInFileArray, FILE** pOutFileArray, const int index );


:davis:
 
 

Recent GIDBlogLast Week of IA Training by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
CD burner wont burn!! robertli55 Computer Hardware Forum 1 18-Jun-2004 10:53
Yet another CD burner problem: Lite-On LSC-24082K Erwin Computer Hardware Forum 1 22-May-2004 11:28
Can't view pages from another machine on the Intranet aevans Apache Web Server Forum 9 14-May-2004 02:26
Re: Programming Techniques WaltP C Programming Language 0 09-Mar-2004 23:56

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:14.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.