Allie H Allie H - 1 month ago 4x
C Question

Check first six characters in csv file for a specific sequence

I'm trying to write a program (obviously new to this) that checks an input file to ensure that it adheres to the specified format. The input file is supposed to be in csv format with the first two rows beginning with the designations "Class" and "Subject", respectively.
I know checking for the "Subject" designation at the beginning of the second line will be a bit more complicated, but I think I can figure out where to start reading/checking for the string by determining the dimensions of the input dataset through calculation of the number of commas and line breaks.
However, I'm getting a little stuck on how to make sure that the first six characters are "Class,".
I was first just trying to figure out how to scan for a commas within the first six characters (see below), and I got stuck there.

// search the first six characters for "Class,"
FILE *input;
int character;
int comma_check = 0;
int i = input[i];
while (i < 6)
character = fgetc(input);
if (character == ',')
if (comma_check == 0)
printf("Input file is not in the correct format.\n");
return 1;

I've read through a number of posts that suggest ways to print to the screen (although I haven't figured out how to just print a specified number of characters rather than through the end of the file), but I don't know how I would go about saving the those first six characters into a string that I could then compare to "Class,". Any help or suggestions would be greatly appreciated. Thank you in advance!


Use fread to read the first 6 characters and compare it with the key. Example:

FILE *input;
int match = 0;
char buf[7] = { 0 };

input = fopen("variation_format_help.txt", "r");
if (!input)
    return 0;

fread(buf, 1, 6, input);
if (strncmp(buf, "Class,", 6) == 0)
    match = 1;
    printf("%s match\n", buf);

At this point you can close the file or continue reading the file. If you want to go back to the beginning of the file then call fseek(input, 0, 0);, there is no need to close the file and open it again.