Hello forum.
I have an issue with a program supposed to take in a user input for a file name, open it, read its contents and finally output the function name(s) and how many source lines of code (for this program, only legitimate semi-colons).
This is an example of a .txt file with a snippet of C code.
Code:
void fillAnArray(int a[])
BEGIN_FCN
int i, j;
fill = -3; /* comment; <- uncounted semi-colon */
for( i = 0, j=2; i < sizeof(a); i++, j--)
a[i] = i + j * fill; /* of course ; a
comment may be a number of
lines; pages, etc etc */
printf (“stuff;”);
return;
END_FCN
successfully, it should output 7 SLOCs, due to 7 counted semi-colons excluding comments.
This is my code so far. It isn't very far, but I have an issue right from the get go.
Code:
#include <stdio.h>
#include <stdlib.h>
#define BEGIN_FCN {
#define END_FCN }
#define MAX 1000
#define INPUT_FILE "example.txt"
int main(void)
{
char fileName[MAX];
char str [MAX];
int begin, end;
int filePrev, fileCur;
int *c, temp1, temp2, length1, length2;
FILE *fp;
printf ("Enter the file name to open: ");
gets(fileName); /* get the file name from stdin */
fp = fopen(fileName, "r");
if (fp == NULL)
{
do
{
printf("\nFile %s could not be opened\n", fileName);
printf ("Enter the file name to open: ");
gets(fileName); /* get the file name from user */
fp = fopen(fileName, "r");
}
while (fp == NULL);
}
printf("\bFile %s is successfully opened\n\n", fileName);
/* perform desired read operations from the file in here */
while (!feof(fp))
{
fgets(str, MAX, fp);
printf("%s", str);
}
fseek(fp, 0, SEEK_SET);
filePrev = fseek(fp, 0, SEEK_SET);
while (!feof(fp))
{
fgets(str, MAX, fp); //Get current string
printf("%s\n", str);
temp1 = strstr(str, "BEGIN_FCN"); //Check if BEGIN_FCN is in string
temp2 = strstr(str, "END_FCN"); //Check if END_FCN is in string
if (temp1 != 0)
{
fseek(fp, 0, SEEK_CUR); //Function name is in the line before
fgets(str, MAX, fp); //String containing function name
printf("%s\n", str);
//fseek(fp, line2, SEEK_SET);
temp1 = strchr(str,'(');
}
}
printf("\n\nComplete couting SLOC of %s", fileName);
fclose(fp);
getchar();
return 0;
}
My issue is after finding the BEGIN_FCN which replaces the { and the END_FCN which replaces the } of functions, finding the proper offset for fseek(fp, offset, SEEK_CUR); so it aims at the beginning of the string right above BEGIN_FCN, which is the string that contains the name of the function.
I want to get the name of the function, and find how many SLOCs there are inside.
It works for this time because if the offset is 0, it is at the start of the file which is already the beginning of the proper string.
Would I use strlen to find the lengths of the line with the function, then the line I read afterwards ("BEGIN_FCN" or "{") then subtract how much from the current fp to end up at the start of the proper string?