Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

C Examples For Working With Files

Check The Number of Arguments

#include 

int main(int argc, char *argv[])
{
    int i;
    fprintf(stdout,
        "The number of command line arguments is %d\n",
        argc);
    fprintf(stdout,"The program name is %s\n",argv[0]);

    for (i = 1; i < argc; i++)
    {
        fprintf(stdout,"%s\n",argv[i]);
    }
    fprintf(stdout,"\n");
    return 0;
}

Count the Number of Occurences of a Character

int main ()
{
  FILE * pFile;
  char c;
  char f = 'a';
  int n = 0;
  char filename[] ="c:\\ct\\bort\\local3.html";

  pFile=fopen (filename,"r");
  if (pFile==NULL) perror ("Error opening file");
  else
  {
    do {
      c = fgetc (pFile);
      if (c == f) n++;
    } while (c != EOF);
    fclose (pFile);
    printf ("File contains %d instances of '%c'\n",n, f);
  }
  return 0;
}

Print File Contents

	char line[133];
	FILE *fp;
	char name[] ="C:\\phrases.txt";

	if((fp=fopen(name, "rt")) == NULL)
	{
		printf("cannot open file %s", name);
		return 0;
	}

	do{
		fgets(line, 132, fp);
		printf( "%s\n", line );

	} while(!feof(fp));

	fclose(fp);

Simple C program that checks for duplicate numbers