I am trying to read the size of the 2 files to determine which of the two are smaller, but the second file always comes out to zero and the first size is not even correct, any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
struct stat buf1;
struct stat buf2;
FILE *fp1, *fp2;
int ch1, ch2;
clock_t elapsed;
char fname1[40], fname2[40];
printf("Enter name of first file:");
fgets(fname1, 40, stdin);
while ( fname1[strlen(fname1) - 1] == '\n')
{
fname1[strlen(fname1) -1] = '\0';
}
printf("Enter name of second file:");
fgets(fname2, 40, stdin);
while ( fname2[strlen(fname2) - 1] == '\n')
{
fname2[strlen(fname2) -1] = '\0';
}
fp1 = fopen(fname1, "r");
if ( fp1 == NULL )
{
printf("Cannot open %s for reading\n", fname1 );
exit(1);
}
fp2 = fopen(fname2, "r");
if (fp2 == NULL)
{
printf("Cannot open %s for reading\n", fname2);
exit(1);
}
//int name1 = fopen(fname1, "r");
//int name2 = fopen(fname2, "r");
stat(fp1, &buf1);
int size1 = buf1.st_size;
stat(fp2, &buf2);
int size2 = buf2.st_size;
printf("Size of file 1: %d\n", size1);
printf("Size of file 2: %d\n", size2);
elapsed = clock(); // get starting time
ch1 = getc(fp1); // read a value from each file
ch2 = getc(fp2);
unsigned long long counter = 0;
unsigned long long total = 0;
while(1) // transform this into a for loop
{
ch1 = getc(fp1);
ch2 = getc(fp2);
if((ch1 ^ ch2) == 0) // try to change this into a for loop?
{
counter++;
}
total++;
if ( ( ch1 == EOF) || ( ch2 == EOF)) // if either file reaches the end, then its over!
{
break; // if either value is EOF
}
}
fclose (fp1); // close files
fclose (fp2);
float percent = (float)counter / (float)total * 100.0f ;
printf("Counter: %u Total: %u\n", counter, total);
printf("Percentage: %.2f%\n", percent);
elapsed = clock() - elapsed; // elapsed time
printf("That took %.4f seconds.\n", (float)elapsed/CLOCKS_PER_SEC);
return 0;
}
Here are the results:
Enter name of first file:air.197901.nc
Enter name of second file:air.197902.nc
Size of file 1: 1340845192
Size of file 2: 0
Counter: 147701939 Total: 1256756880
Percentage: 11.75
That took 105.8533 seconds.
Your code is not even calling fstat. You're calling stat but passing a FILE pointer to it rather than a pathname. You need to either do:
stat(fname1, &buf1);
or:
fstat(fileno(fp1), &buf1);
This mistake should have produced an error (or at least a warning) from the compiler.
Also, you should be checking the return value of stat or fstat.
Related
I want to give input as line number and get output as the corresponding text for that line number in a text file.
Sample text file:
Hi this is Stefen
Hi How are you
Example input:
Enter the line number:2
Expected Output:
Hi How are you
My program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
perror("Unable to open the file\n");
exit(1);
}
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf("%s\n", buf);
print("~~~~\n");
}
fclose(fp);
return 0;
}
Output I got:(The entire file with the separator ~~~~ below each line)
Hi this is Stefen
~~~~
Hi How are you
~~~~
Can anyone please tell me how to do this?
As pmg suggests, would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define INFILE "sample.txt"
int main()
{
FILE *fp;
char buf[BUFSIZ];
int count = 0, n;
fp = fopen(INFILE, "r");
if (fp == NULL) {
perror(INFILE);
exit(1);
}
printf("Enter the line number: ");
fgets(buf, sizeof buf, stdin);
n = (int)strtol(buf, (char **)NULL, 10);
while (fgets(buf, sizeof buf , fp) != NULL){
if (++count == n) {
printf("%s", buf);
break;
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Best to use a second file
check if you're at \n that means new line and increment a variable like "line"
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
ptr2 = fopen("c:\\CTEMP\\newfile.txt", "w");
if(ptr2==NULL)
printf("second error opening newfile");
while (!feof(ptr1))
{
ch = fgetc(ptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file newfile.c
fputc(ch, ptr2);
}
}
fclose(ptr1);
fclose(ptr2);
"detele_line" variable is for the user to inter.
The easiest way is using array to save the lines, then print the certain line.
#include <stdio.h>
#define M 10010
#define N 256
char buf[M][N];
int main(){
FILE *file;
char fileName[50] = "sample.txt";
file = fopen(fileName, "r");
if(file == NULL)
return 1;
int n = 0;
while(fgets(buf[n], N, file) != NULL){
n++;
}
fclose(file);
int i, x;
printf("Example input:\nEnter the line number:");
scanf("%d", &x);
printf("Expected Output:\n%s", buf[x-1]);
return 0;
}
I'm studying textfile topic in C and I have got a question: what can I use instead of __fpurge(stdin); but make this function work like __fpurge(stdin); and I am not allowed to include <stdlib.h> in this program. I have read this c - need an alternative for fflush but as long as I'm not allowed to #include <stdlib.h> so I can't use strtol.
void generateBill() {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
printf("ID\tName\tPrice\n\n");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
printf("%d\t", t.pid);
printf("%s\t", t.pname);
printf("%d\t\t\t\n", t.pprice);
total = total + t.pprice;
}
printf("\n\n=================== Total Bill Amount %d\n\n", total);
fclose(fp);
if (total != 0) {
//__fpurge(stdin);
printf("\n\n\n Do you want to generate Final Bill[1 yes/any number to no]:");
scanf("%d", &ch1);
if (ch1 == 1) {
brel = billFileNo();
sprintf(billname, "%s%d", " ", brel);
strcat(billname, "dat");
fp = fopen(fbill, "rb");
fp1 = fopen(billname, "wb");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp);
fclose(fp1);
fp = fopen(fbill, "wb");
fclose(fp);
}
total = 0;
}
}
for a replacement for __fpurge(stdin) suggest:
int ch;
while( (ch = getchar() ) != EOF && ch != '\n' ){;}
which only requires #include <stdio.h>
__fpurge is a non-standard function only available on some systems (glibc 2.1.95, IBM zOS...) that discards input read into the stream buffer not yet consumed by getc().
As explained in the linux manual page, Usually it is a mistake to want to discard input buffers.
You read user input with scanf(), which stops scanning input when the requested conversion is completed, for example %d stops reading the characters typed by the user when it reads a character that cannot continue the number and leaves this character in the input stream. Since stdin is usually line buffered when attached to a terminal, you should just read and discard any remaining bytes in the line input by the user after you process the input.
Here is a simple function for this purpose:
int flush_input(FILE *fp) {
int c;
while ((c = getc(fp)) != EOF && c != '\n')
continue;
return c;
}
You would call this function after processing user input and you should test the return value of scanf() to ensure the user input had the expected syntax.
Here is a modified version of you function:
#include <errno.h>
#include <string.h>
// return a non zero error code in case of failure
int generateBill(void) {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
if (fp == NULL) {
fprintf(sdterr, "cannot open %s: %s\n", fbill, strerror(errno));
return 1;
}
printf("ID\tName\tPrice\n\n");
while (fread(&t, sizeof(t), 1, fp) == 1) {
printf("%d\t", t.pid);
printf("%s\t", t.pname);
printf("%d\t\t\t\n", t.pprice);
total = total + t.pprice;
}
printf("\n\n=================== Total Bill Amount %d\n\n", total);
if (total != 0) {
int res;
printf("\n\n\n Do you want to generate Final Bill[1 yes/any number to no]:");
while ((res = scanf("%d", &ch1)) == 0) {
fprintf("Invalid input. Try again\n");
flush_input(stdin);
}
flush_input(stdin);
if (res == EOF) {
fprintf("premature end of file on input\n");
fclose(fp);
return 2;
}
if (ch1 == 1) {
brel = billFileNo();
snprintf(billname, sizeof billname, "bill-%d-dat", brel);
rewind(fp);
fp1 = fopen(billname, "wb");
if (fp1 == NULL) {
fprintf(sdterr, "cannot open %s: %s\n", billname, strerror(errno));
fclose(fp);
return 1;
}
while (fread(&t, sizeof(t), 1, fp) == 1) {
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp1);
}
}
fclose(fp);
return 0;
}
I have copied the contents of a file to another file and I am trying to get the line, word, and character count. The code I have right now displays the number of lines and words in the file content. Now I need to display the character count but I am unsure of how to do that. I am guessing a for loop? But I am not sure.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_WORD_LEN 100
#define MAX_LINE_LEN 1000
#define ipsumFile "Lorem ipsum.txt"
#define ipsumCopy "Lorem ipsum_COPY.txt"
int wordCount(FILE *fp);
int charCount(FILE *fp);
int sendContentTo(FILE *fp, FILE *out);
int getWordAt(FILE *fp, int pos, char *word);
int appendToFile(char *fileName, char *newText);
int main(void)
{
FILE *fp, *fp2; //"file pointer"
int ch; //place to store each character as read
//open Lorem ipsum.txt for read
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
//open Lorem ipsumCopy for writing
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
//print out and count all words in Lorem ipsum.txt
int numOfWords = wordCount(fp);
//print out and count all lines in Lorem ipsum.txt
int numOfLines = sendContentTo(fp, stdout);
//copy the content of Lorem ipsum.txt into a new file (ipsumCopy)
numOfLines = sendContentTo(fp, fp2);
fclose(ipsumFile);
fclose(ipsumCopy);
// close Lorem ipsum.txt
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
if (fclose(fp2) != 0)
fprintf(stderr, "Error closing copy\n");
return 0;
}
int sendContentTo(FILE *in, FILE *out)
{
fprintf(stdout, "Performing file copy...\n\n");
//start at the beginning of the file
rewind(in);
// array to hold one line of text up to 1000 characters
char line[MAX_LINE_LEN];
int lineCount = 0;
// read one line at a time from our input file
while (fgets(line, MAX_LINE_LEN, in) != NULL)
{
//send line we just read to output.
fprintf(out, "%s", line);
//count the lines
lineCount++;
}
fprintf(stdout, "\nFinished line count.\n");
fprintf(stdout, "Count is: %d.\n\n", lineCount);
// Return how many text lines
// we've processed from input file.
return lineCount;
}
// Read content from file one character at a time.
// Returns number of total characters read from the file.
int charCount(FILE *fp)
{
fprintf(stdout, "Performing char count...\n\n");
rewind(fp);
int charCount = 0;
char ch;
//print out each character, and return the
// number of characters in the file.
fprintf(stdout, "\nFinished character count. \n");
fprintf(stdout, "Count is: %d. \n\n", charCount);
return charCount;
}
// Read content from file one word at a time.
// Returns number of total words read from the file.
int wordCount(FILE *fp)
{
fprintf(stdout, "Performing word count...\n\n");
rewind(fp);
char word[MAX_WORD_LEN];
int wordCount = 0;
while (fscanf(fp, "%s", word) == 1)
{
// Send entire word string
// we just read to console
puts(word);
//count the word
wordCount++;
}
fprintf(stdout, "\nFinished word count.\n");
fprintf(stdout, "Count is: %d.\n\n", wordCount);
return wordCount;
}
You don't need to write different function for counting the number of lines, words, and characters in a file. You can do it in a single parsing of file character by character and while parsing, in order to copy the content of file to another file, you can write the characters to another file. You can do:
#include <stdio.h>
#include <stdlib.h>
int count_and_copy(const char * ipsumFile, const char * ipsumCopy)
{
unsigned int cCount = 0, wCount = 0, lCount = 0;
int incr_word_count = 0, c;
FILE *fp, *fp2;
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
while((c = fgetc(fp)) != EOF)
{
fputc(c, fp2); // write character c to the copy file
cCount++; // character count
if(c == '\n') lCount++; // line count
if (c == ' ' || c == '\n' || c == '\t')
incr_word_count = 0;
else if (incr_word_count == 0) {
incr_word_count = 1;
wCount++; // word count
}
}
fclose (fp);
fclose (fp2);
printf ("Number of lines : %u\n", lCount);
printf ("Number of words : %u\n", wCount);
printf ("Number of characters : %u\n", cCount);
return 0;
}
int main()
{
/* Assuming, you want to count number of lines, words
* and characters of file1 and copy the contents of file1
* to file2.
*/
count_and_copy("file1", "file2");
return 0;
}
I suppose that the following approach will work:
void *cw(const char *fname)
{
FILE *f = fopen(fname, "r");
if (f == NULL) {
fprintf(stderr, "fopen(%s): %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
int bc = 0; /* bytes counter */
int wc = 0 ; /* words counter */
int nlc = 0; /* new lines counter */
const int in_word_state = 0;
const int out_word_state = 1;
int state = out_word_state;
int c = 0;
for (;;) {
c = fgetc(f);
if (ferror(f) != 0) {
perror("fgetc");
goto error;
}
if (feof(f))
break;
if (c == '\n')
nlc++;
if (c == ' ' || c == '\t' || c == '\n')
state = out_word_state;
if (state == out_word_state) {
state = in_word_state;
wc++;
}
bc++;
}
if (fclose(f) == EOF) {
perror("fclose");
goto error;
}
printf("w: %d, c: %d, l:%d\n", wc, bc, nlc);
error:
if (f != NULL) {
if (fclose(f) == EOF) {
perror("fclose");
}
}
exit(EXIT_FAILURE);
}
I am reading a time from a file and then trying to convert the read time to seconds. Is there a simpler way to convert the time stamp? My method seems to be inefficient. What would you suggest be the best method when writing to a file?
Sample File
My test file
00:19.1 123456
00:35.4 testing whitespace end
Desired Output
1: My test file
2: 00:19.1
3: 00:35.4
Code:
#include <stdio.h>
#define MAXC 1024 // define constants, don't use magic number in code
#define MAXN 40
int main (int argc, char **argv) {
char buf[MAXC] = ""; // buffer to hold each line -- size as reqd
char filename[MAXN];
int line = 1;
int replace_line;
FILE *fp, *fp2;
printf("Please enter a file name: ");
scanf("%s",&filename);
fp = fopen(filename,"r+");
if (!fp) // validate file open for reading
{
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
//printf("Enter a increment of time: ");
//scanf("%d", &increment);
while (fgets (buf, sizeof buf, fp)) // read each line in file
{
char et[MAXC] = ""; // buffer for holding time
char etR[MAXC] = "";
char time[7] = "";
int filler = 0;
if (line == 1) // if 1st line, just print
{
printf ("%d : %s", line, buf); // note: \n included by fgets
//fprintf(fp2,"%s",buf);
} // end of if first line
else
{
if (sscanf (buf, "%s", et) != 1) // parse up to first whitespace
{
fprintf (stderr, "error: invalid conversion, line %d\n", line);
return 1;
}
printf ("%d : %s\n", line, et); //output elapsed time only
while(filler < 7)
{
time[filler] = et[filler];
filler++;
}
time[1] = time[1] - '0'; //Leading Minute (error if over 6)
time[2] = time[2] - '0'; //Minute
time[4] = time[4] - '0'; //Leading Second (Add to minute if over 6)
time[5] = time[5] - '0'; //Second (Add to LS if over 9)
time[7] = time[7] - '0'; //fraction of a second (Add to S if over 9)
float timeInSeconds;
char minuteHolder[2];
sprintf(minuteHolder,"%d%d",time[1],time[2]);
int minute;
minute = (minuteHolder[0]*10) + minuteHolder[1];
printf("\n%d\n",minute);
//getting 539 , minutes on every line???
} //end of else
line++; // increment line count
} // end of while parsing file
rewind(fp);
if (fp != stdin) // close file if not stdin
{
fclose (fp);
}
return 0;
}
convert source string: "00:19.1 123456"
to dest stringļ¼ "1. 00:19.1"
1st : we should find the black character pos:
*char pblack = strchr(buf, ' ');
now pblack is point to " 123456".
2nd: we set the old string to the new string:
becase a string is endwith '\0',
so we set: pblack[0] = '\0';
now , we have the code:
#include <stdio.h>
#define MAXC 1024 // define constants, don't use magic number in code
#define MAXN 40
int main(int argc, char **argv) {
char buf[MAXC] = ""; // buffer to hold each line -- size as reqd
char filename[MAXN];
int line = 1;
int replace_line;
//FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
//FILE *fp = fopen("test.txt","r");
FILE *fp, *fp2;
printf("Please enter a file name: ");
scanf("%s", &filename);
fp = fopen(filename, "r+");
//fp2 = fopen("datadump.txt","w");
if (!fp) // validate file open for reading
{
fprintf(stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
//printf("Enter a increment of time: ");
//scanf("%d", &increment);
while (fgets(buf, sizeof buf, fp)) // read each line in file
{
char et[MAXC] = ""; // buffer for holding time
char etR[MAXC] = "";
char time[7] = "";
int filler = 0;
if (line == 1) // if 1st line, just print
{
printf("%d : %s", line, buf); // note: \n included by fgets
//fprintf(fp2,"%s",buf);
} // end of if first line
else
{
char *pblack = strchr(buf, ' '); // get chr ' ' pos
pblack[0] = 0; // set ' ' to '\0', get the new string
printf("%d : %s\n", line, buf);
} //end of else
line++; // increment line count
} // end of while parsing file
rewind(fp);
//fp2 = fopen("replica.c","w");
//replacement code
/*
flcose(fp);
fclose(fp2);
remove(filename(;
rename("replica.c",filename);
//if you to show them new file fflush stdin and repeat while
//fp = fopen(filename, "r");
//while loop
*/
if (fp != stdin) // close file if not stdin
{
fclose(fp);
//fclose (fp2);
}
return 0;
}
If the time format is the same after the incremental, you can replace the time field with fseek without rewriting the whole file.
An overall example is shown. Please change details.
try this
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXC 1024 //input buffer size
#define MAXLINE 1024 //max number of line
int main (int argc, char **argv) {
char filename[FILENAME_MAX+1+1];//+1: newline, +1: NUL
char buf[MAXC] = "";
char time_field[7+1];//mm:ss.s, +1: NUL
unsigned char ch;
long pos[MAXLINE];//save file positions
int line = 0; //start with 0 in program
int replace_line; //input replace line number
int increment; //input incremant second.
FILE *fp;
printf("Please enter a file name: ");
fgets(filename, sizeof filename, stdin);
filename[strcspn(filename, "\n")] = 0;//chomp newline
fp = fopen(filename, "r+");
if (!fp){
fprintf (stderr, "error: file open failed '%s'.\n", filename);
return 1;
}
//display file & store file position each line
pos[line] = ftell(fp);
while (fgets (buf, sizeof buf, fp)){
if(++line == MAXLINE){
fprintf (stderr, "error: file too long.\n");//Need change the program. expand array or use malloc and realloc
return 2;
}
pos[line] = ftell(fp);
if (!isdigit(ch = *buf)){//If it does not start with a numerical value Output as it is
printf("%d : %s", line, buf); //note: \n included by fgets
} else {
if(sscanf(buf, "%7s%c", time_field, &ch)==2 && isspace(ch)){
printf ("%d : %s\n", line, time_field);
} else {
fprintf (stderr, "error: invalid time format '%s'", buf);
return 3;
}
}
}
printf("Enter a number of edit line: ");
scanf("%d", &replace_line);
printf("Enter a increment of time: ");
scanf("%d", &increment);//sec
if(fseek(fp, pos[replace_line-1], SEEK_SET)==0){//-1: 0 start in program, 1 start in input
int m, s, ds, seconds;
fscanf(fp, "%s", time_field);
if(sscanf(time_field, "%d:%d.%d", &m, &s, &ds)!=3){
fprintf (stderr, "error: invalid time format '%s' at %d line.\n", time_field, replace_line);
return 3;
}
seconds = m * 60 + s + increment;
m = seconds / 60;
s = seconds % 60;
if(m > 99 || seconds < 0){
fprintf (stderr, "error: Can't change time format.\n");//It is necessary to rewrite the whole file.
return 4;
}
fseek(fp, pos[replace_line-1], SEEK_SET);
fprintf(fp, "%02d:%02d", m, s);fflush(fp);
} else {
fprintf (stderr, "error: file seek failed to '%d' line.\n", replace_line);
return 5;
}
fclose(fp);
return 0;
}
I am trying to write a program to compile with Xeon Phi and it says there is a segmentation fault? I think it is when I try to fill the arrays with the getc function. I have written this code several different formats, and I understand that this might not be the most efficient, but I need to test it out to see if it will work by parallelizing it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//#include <omp.h>
int main()
{
struct stat buf1;
struct stat buf2;
FILE *fp1, *fp2;
int ch1, ch2;
clock_t elapsed;
char fname1[40], fname2[40];
printf("Enter name of first file:");
fgets(fname1, 40, stdin);
while (fname1[strlen(fname1) - 1] == '\n')
{
fname1[strlen(fname1) -1] = '\0';
}
printf("Enter name of second file:");
fgets(fname2, 40, stdin);
while (fname2[strlen(fname2) - 1] == '\n')
{
fname2[strlen(fname2) -1] = '\0';
}
fp1 = fopen(fname1, "rb");
if (fp1 == NULL)
{
printf("Cannot open %s for reading\n", fname1);
exit(1);
}
fp2 = fopen(fname2, "rb");
if (fp2 == NULL)
{
printf("Cannot open %s for reading\n", fname2);
exit(1);
}
stat(fname1, &buf1);
size_t size1 = buf1.st_size;
stat(fname2, &buf2);
size_t size2 = buf2.st_size;
printf("Size of file 1: %zd\n", size1);
printf("Size of file 2: %zd\n", size2);
elapsed = clock(); // get starting time
size_t smallest = 0;
if(size1 < size2)
{
smallest = size1;
}
else
{
smallest = size2;
}
printf("Smallest Value: %zu\n", smallest);
size_t i, j, k;
size_t data[smallest];
size_t arry1[smallest];
size_t arry2[smallest];
unsigned long long counter = 0;
for(i = 0; i < smallest; i++)
{
data[i] = 1;
arry1[i] = getc(fp1);
arry2[i] = getc(fp2);
}
//#pragma omp for //reduction(+:counter)
for(k = 0; k < smallest; k++)
{
if((arry1[k] ^ arry2[k]) == 0)
{
counter+= data[k];
}
}
fclose (fp1); // close files
fclose (fp2);
float percent = (float)counter / (float)smallest * 100.0f;
printf("Counter: %zu Total: %zu\n", counter, smallest);
printf("Percentage: %.2f%\n", percent);
elapsed = clock() - elapsed; // elapsed time
printf("That took %.2f seconds.\n", (float)elapsed/CLOCKS_PER_SEC);
return 0;
}
Thanks for your help in advance!
You cannot declare an array with a size that's not known at compile time:
int smallest;
smallest = .... // some computation
size_t data[smallest]; // this is wrong!
You should instead use malloc() to accomplish that:
size_t *data;
smallest = ... // whatever
data = malloc(smallest * sizeof(size_t));
This loop:
while (fname1[strlen(fname1) - 1] == '\n')
fname1[strlen(fname1) -1] = '\0';
will read off the start of the string if the line was blank (i.e. "\n"). Change while to if.
Also, check that smallest > 0 before declaring the VLAs.
It might be insightful to output the value of smallest, typical systems default to a stack size of somewhere between 1MB and 8MB, so perhaps you cause a stack overflow here. You could eliminate this possibility by using malloc, as ocho88 suggests (but without the bogus cast):
size_t *data = malloc(smallest * sizeof *data);
size_t *arry1 = malloc(smallest * sizeof *arry1);
size_t *arry2 = malloc(smallest * sizeof *arry2);
if ( !data || !arry1 || !arry2 )
// exit with out-of-memory error
I'm not sure why you use a size_t to store the result of getc.
If this does not solve the problem then it would be useful to identify which line is segfaulting. If you can't get a debugger working, then you can output (to stderr, or to stdout with fflush) to find out where it is getting up to.