Home > Software engineering >  Creating 1000 text files in C
Creating 1000 text files in C

Time:07-07

I am learning C language. Here is a simple program I did to create 1000 text files.

#include <stdio.h>
#include <string.h> 

char * create_filename(char *, char *, int);

int main(void)
{ 
    char prefix_name[50] = "file_no_";
    char snum[5];
    int no_of_files = 1000;

    FILE * fp = NULL;


    for (int i = 0; i < no_of_files; i  )
    {
        fp = fopen( create_filename(prefix_name, snum, i   1), "w");
        fprintf(fp, "This is file no %d", i 1);
        fclose(fp);
        fp = NULL;
        strcpy(prefix_name, "file_no_");
    }
    
    return 0;
   
}  

char * create_filename(char * prefix_name, char * snum, int i)

{

    sprintf(snum, "%d", i);
    strcat(prefix_name, snum);
    strcat(prefix_name, ".txt");

    return prefix_name;
}

This runs as expected. But I want to know, how can I make this more efficient and as portable as possible. If I want to scale this up to, say 10000 text files, are there other approaches which will be better ?

Thanks

CodePudding user response:

how can I make this more efficient and as portable as possible.

  1. More error checking. Example: a failed fopen() can readily occur.

  2. Realize that a huge amount of time will occur in fopen() and local code likely will have scant time improvements.

  3. Avoid re-writing the prefix.

  4. Use a helper function.

Example:

// Return count of successfully written files.
int create_many_files(const char *prefix, int count, const char *suffix) {
  int n;
  int len = snprintf(NULL, 0, "%s%n%d%s", prefix, &n, count, suffix);
  if (len < 0) {
    return 0;
  }

  // Use len to determine longest name and use a VLA or allocation.
  // Consider using a fixed array when len is not too big.
  char *filename = malloc((size_t)len   1u);
  if (filename == NULL) {
    return 0;
  }
  strcpy(filename, prefix);
  char *offset = filename   n;

  for (int i = 0; i < count; i  ) {
    sprintf(offset, "%d%s", i   1, suffix);
    FILE *fp = fopen(filename, "w");
    if (fp == NULL) {
      free(filename);
      return i;
    }
    fprintf(fp, "This is file no %d", i   1);
    fclose(fp);
  }

  free(filename);
  return count;
}

Other potential error checks:

  • prefix == NULL
  • cout < 0
  • suffix == NULL
  • fprintf() < 0
  • fclose() != 0
  •  Tags:  
  • c
  • Related