Fscanf Seg Error - c

Working on a project where I have to have a file that is generated numbers. First line is a generated int. Followed by a floats (separate lines). (I'm doing it separate lines because I feel it makes more sense as I have to read it two different ways for the bin packing problems which I need this for... Like one way of reading one at a time and another storing it in an array.. But want to get this down first)
Getting a seg fault when I try to read my file for a float after reading an int. Edit: Error occurs in readOffline.
int randomFunction()
{
FILE *fp;
int i;
fp = fopen("theItems.txt", "w" );
if (fp == NULL)
printf("Error: file can't be opened.\n");
srand(time(NULL) );
int random_number = rand();
printf("Random Number %d\n", random_number);
fprintf(fp,"%d",random_number);
fclose(fp);
fp = fopen("theItems.txt", "a");
int numberOfItems = rand();
printf("NumberOfItems: %d\n",numberOfItems);
for(i = 0; i < 10; i++)
{
fp = fopen("theItems.txt", "a");
float number = (float)rand()/(float)(RAND_MAX);
fprintf(fp,"%f",number);
fprintf(fp,"%s", "\n");
fclose(fp);
}
return numberOfItems;
}
void readOffline( int numberOfItems)
{
FILE *fp;
int n = 0,i;
float nu = 0.00;
fp = fopen("theItems.txt", "r");
if (fp == NULL)
printf("Error: file can't be opened.\n");
fseek(fp,SEEK_SET,0);
fscanf(fp,"%d",&n);
printf("Number read: %d\n", n);
float array[numberOfItems];
// for(i = 0; i < 3; i++)
// {
fscanf(fp,"%f",&nu);
// array[i] = nu;
// }
fclose(fp);
printf("Int:%d\n", n);
int j;
// for(j = 0; j < 3; j++)
// printf("Float Number:%f\n", array[j]);
}
int main()
{
int numberOfItems = randomFunction();
readOffline(numberOfItems);
return 0;
}
Just trying to get an understanding why it causes a seg error when I // it out I can get it to read my int but sometimes it isn't the right int read. But yeah.
Please let me know if I need any more details or need to be more clear anywhere

You have multiple issues in your code:
You open the output file multiple times in randomFunction(), you even leak a stream handle and leave it open.
You do not exit the function when fopen() returns NULL. The rest of the code invokes undefined behavior if fp == NULL.
The same problem is present in readOffline(): if fp == NULL, you should return from the function immediately.
you do not output a linefeed after the first random number in the output file.
you always output 10 random numbers.
most importantly: the random number returned by the randomFunction() is potentially huge, allocating an array with local storage larger than a few megabytes is likely to cause undefined behavior. Try and reduce the maximum random number of values.
Here is a proposed correction:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randomFunction(void) {
FILE *fp;
int i;
fp = fopen("theItems.txt", "w");
if (fp == NULL) {
printf("Error: file can't be opened.\n");
return -1;
}
srand(time(NULL));
int random_number = rand();
printf("Random Number %d\n", random_number);
fprintf(fp, "%d\n", random_number);
int numberOfItems = 1 + rand() % 100; /* between 1 and 100 */
printf("NumberOfItems: %d\n", numberOfItems);
for (i = 0; i < numberOfItems; i++) {
float number = rand() / (float)(RAND_MAX);
fprintf(fp, "%f\n", number);
}
fclose(fp);
return numberOfItems;
}
void readOffline(int numberOfItems) {
FILE *fp;
int n = 0, i;
fp = fopen("theItems.txt", "r");
if (fp == NULL) {
printf("Error: file can't be opened.\n");
return;
}
fscanf(fp, "%d", &n);
printf("Number read: %d\n", n);
float array[numberOfItems];
for (i = 0; i < numberOfItems; i++) {
if (fscanf(fp, "%f", &array[i]) != 1)
break;
}
fclose(fp);
printf("Int:%d\n", n);
for (int j = 0; j < i; j++) {
printf("Float Number %d: %f\n", j, array[j]);
}
}
int main(void) {
int numberOfItems = randomFunction();
readOffline(numberOfItems);
return 0;
}
Note that I kept your semantics: the random number at the start of the file is not the number of floating point values that follow. I suspect it should be?

I would say that depending on the particular compiler that you are using, then this could be a problem in setting up the actual array. This is (as an example) discussed in Variable Sized Arrays vs calloc in C From the discussions, you should use calloc and free. Another point is that you need to make sure that your value is greater than 3 and not too big. Since the array is only in the local scope of readOffline(), you should not connect it to the variable numberOfItems.
float array[3];
for(i = 0; i < 3; i++)
{
fscanf(fp,"%f",&nu);
array[i] = nu;
}

Related

Saving integers from a file into an array

I was hoping to get a bit of help, I am implementing an inversion counter algorithm to take in 50,000 intergers and display the inversions and time it took to run the algorithm, I am having a hard time allocating and saving the integers from the file into an array. My code complies and runs but nothing happens
here is what I have:
int main(int argc, char** argv)
{
int n, i;
int inversions=0;
int *A;
FILE *file;
char filename[100];
clock_t start, end;
double totalTime;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if(file == NULL)
{
printf("Error opening file!\n");
return 0;
}
fscanf(file, "%d", &n);
A = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
fscanf(file, "%d", &A[i]);
}
start = clock();
inversions = countInversionsBruteForce(A, n);
end = clock();
totalTime = (double) (end - start) / CLOCKS_PER_SEC;
printf("Brute Force Algorithm\n");
printf("Number of inversions: %d\n", inversions);
printf("Execution time: %f\n", totalTime);
I think I have noth allocated array size and saved it properly
Your program is incomplete so I was not able to compile it. Minimized the problem to just loading the data into your array:
Formatted code for readability.
Generated a suitable input file. Most likely this is your problem but you have not shared your input sample with us.
Added missing include files.
Remove argc, argv as you not using them.
Minimize scope of variables. Use size_t instead of int for unsigned values.
Max string size on obtaining file name
Check return value for scanf(), fopen(), fscanf().
Printing out the data read to demonstrate it's working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Enter filename: ");
char filename[100];
if(scanf("%99s", filename) != 1) {
printf("scanf failed\n");
return 1;
}
FILE *file = fopen(filename, "r");
if(!file) {
printf("Error opening file!\n");
return 1;
}
size_t n;
fscanf(file, "%zu", &n);
if(!n) {
printf("n must be positive");
return 1;
}
int *A = malloc(n * sizeof(*A));
for(size_t i = 0; i < n; i++)
if(fscanf(file, "%d", &A[i]) != 1) {
printf("fscanf() failed\n");
return 1;
}
printf("n = %zu\n", n);
printf("A = ");
for(size_t i = 0; i < n; i++)
printf("%d%s", A[i], i + 1 < n ? ", " : "\n");
}
with 1.txt as:
4
1
2
3
4
a sample session looks like this:
Enter filename: 1.txt
n = 4
A = 1, 2, 3, 4

Segmentation fault when accessing array via fscanf

I'm trying to scan integers from a file, then add them to an array. But every time I run the program I get a segmentation fault. Why is this?
int main(void) {
FILE *file;
int num_in;
int numbers[10000];
file = fopen("/Users/foo/aa/extra/sort/rand10k", "r");
if (file == NULL)
{
perror("Error opening and reading file\n");
return 1;
}
int i = 0;
while (fscanf(file, "%d", &num_in))
{
numbers[i] = num_in;
i++;
}
for (int i = 0; i < 10000; i++)
{
printf("%d\n", numbers[i]);
}
}
The file in question has 10,000 integers in random order:
The condition in the while loop is incorrect
while (fscanf(file, "%d", &num_in))
It is evaluated to true even when EOF occurs.
Instead you need to write
while ( i < 10000 && fscanf(file, "%d", &num_in) == 1 )
After that you should write for example
for (int j = 0; j < i; j++)
{
printf("%d\n", numbers[j]);
}

How to read data from file with fscanf in c-language

I want to import numbers (40000 in total, space-separated) (format: 2.000000000000000000e+02) with "fscanf" and put it in a 1D-Array. I tried a lot of things, but the numbers I am getting are strange.
What I've got until now:
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
float arr[40000];
fscanf(pixel,"%f", arr);
for(int i = 0; i<40000; i++)
printf("%f", arr[i]);
}
I hope somebody can help me, I am a beginner ;-)
Thank you very much!!
Instead of:
fscanf(pixel,"%f", arr);
which is the exact equivalent of this and which read only one single value:
fscanf(pixel,"%f", &arr[0]);
you want this:
for(int i = 0; i<40000; i++)
fscanf(pixel,"%f", &arr[i]);
Complete code:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
if (pixel == NULL) // check if file could be opened
{
printf("Can't open file");
exit(1);
}
float arr[40000];
int nbofvaluesread = 0;
for(int i = 0; i < 40000; i++) // read 40000 values
{
if (fscanf(pixel,"%f", &arr[i]) != 1)
break; // stop loop if nothing could be read or because there
// are less than 40000 values in the file, or some
// other rubbish is in the file
nbofvaluesread++;
}
for(int i = 0; i < nbofvaluesread ; i++)
printf("%f", arr[i]);
fclose(pixel); // don't forget to close the file
}
Disclaimer: this is untested code, but it should give you an idea of what you did wrong.
You need to call fscanf() in a loop. You're just reading one number.
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
if (!pixel) {
printf("Unable to open file\n");
exit(1);
}
float arr[40000];
for (int i = 0; i < 40000; i++) {
fscanf(pixel, "%f", &arr[i]);
}
for(int i = 0; i<40000; i++) {
printf("%f", arr[i]);
}
printf("\n");
}

How to read floats from file in c?

I am struggling with reading floats from a file which I created during the program lifetime. I was trying to rewind the file, I was trying to open and close file before reading it, I was trying to put values directly in the table and by another variable. Idk what can I do more, what's wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
float *tab;
float x = 0.0;
int i, size;
FILE *fp;
fp = fopen("data.txt", "w+");
if (fp == NULL) {
printf("Error");
system("PAUSE");
exit(1);
}
printf("Size of table: ");
scanf("%d", &size);
tab = (int*)malloc(size * sizeof(int));
for (i = 0; i < size; i++) {
tab[i] = (8.0 - 2.0) * (float)rand() / RAND_MAX + 2.0;
fprintf(fp, "%.2f ", tab[i]);
}
for (i = 0; i < size; i++) {
printf("%.2f ", tab[i]);
}
printf("\n");
fp = fclose;
fp = fopen("data.txt", "w+");
tab = realloc(tab, 2*size);
for (i = 0; i < size * 2; i+=2) {
fscanf(fp, "%f", &x);
printf("%.2f ", x);
//tab[i + 1] = tab[i] / 2;
}
/*for (i = 0; i < size * 2; i++) {
printf("%.2f \n", tab[i]);
}*/
fp = fclose;
printf("\n");
system("PAUSE");
return 0;
}
There are a number of problems in this code. First, as noted in the comments, the initial allocation is wrong. You are allocating space for floats, not ints. You could have avoided this problem entirely if you had written the call to malloc() like this:
tab = malloc(sizeof(*tab) * size);
Here, the result of malloc() is not cast, since it is not necessary in C. Also, note that instead of using an explicit type for the argument to the sizeof operator, the identifier is used instead. This guarantees that whatever the type of tab, which must be a pointer, the result of sizeof will be correct. Also, you should always check to see if an allocation was successful.
fp = fclose is just wrong. This should be fclose(fp). After this, when you open the file again with "w+", the file is truncated to zero length, and you lose the data that was previously written. Since the file has already been opened with "w+", just use rewind(fp) here.
For the reallocation that you do, aside from that the arguments are not quite right here, there is a potential problem that you should be aware of. realloc() can return a null pointer in the event of an allocation error. If this happens, and you are directly assigning the result of realloc() to the pointer for which you are reallocating (tab), then you will lose the reference to previously allocated memory. This is a memory leak, and lost data. The way to do this is to store the result of realloc() in a temporary pointer, which you test. If the temporary pointer is a null pointer, there was an error; otherwise you can safely assign the return value to the original pointer.
And as already noted, when you call fclose() the final time, it needs to be fclose(fp).
Here is a modified code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
float *tab, *temp; // added temp for realloc() check
float x = 0.0;
int i, size;
FILE *fp;
fp = fopen("data.txt", "w+");
if (fp == NULL) {
printf("Error");
system("PAUSE");
exit(1);
}
printf("Size of table: ");
scanf("%d", &size);
/* You should always check for allocation errors */
if ((tab = malloc(sizeof(*tab) * size)) == NULL) {
fprintf(stderr, "Error in initial allocation\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < size; i++) {
tab[i] = (8.0 - 2.0) * (float)rand() / RAND_MAX + 2.0;
fprintf(fp, "%.2f ", tab[i]);
}
for (i = 0; i < size; i++) {
printf("%.2f ", tab[i]);
}
printf("\n");
// fclose(fp); // not fp = fclose;
// fp = fopen("data.txt", "w+"); // when you reopen, the file is truncated
rewind(fp); // but just do this
/* Fixed this reallocation */
temp = realloc(tab, sizeof(*tab) * size * 2);
if (temp == NULL) {
fprintf(stderr, "Error in reallocation\n");
exit(EXIT_FAILURE);
}
tab = temp;
for (i = 0; i < size * 2; i+=2) {
fscanf(fp, "%f", &x);
printf("%.2f ", x);
//tab[i + 1] = tab[i] / 2;
}
/*for (i = 0; i < size * 2; i++) {
printf("%.2f \n", tab[i]);
}*/
fclose(fp); // not fp = fclose;
printf("\n");
system("PAUSE");
return 0;
}
Sample interaction:
Size of table: 10
2.65 5.67 5.21 3.22 3.07 4.29 5.96 5.96 5.15 7.36
2.65 5.67 5.21 3.22 3.07 4.29 5.96 5.96 5.15 7.36

Error when trying to read in numbers from txt file in C

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

Resources