holta73
holta73

Reputation: 13

Segmentation fault while trying to use fscanf

In this program i'm trying to read a double and a char array from a file and print out the lines that have a double value more than the one entered into the argument. It compiles fine but when I run it I get the error :Segmentation fault(core dumped)

This is the program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char **argv[]) {


if(argc != 2)
        printf("enter 2 arguments\n");
else {
        int r;
        double tDate = atof(*argv[1]);
        double date = 0;
        char event[] = "";
        FILE *fp = fopen("tickler.dat","r");

        if( fp == NULL ) {
                perror("Error while opening the file.\n");
                exit(EXIT_FAILURE);
        }

        while(r = fscanf(fp, "%lf %s\n", &date, event) != EOF) {

                if(date > tDate)
                        printf("%d - %s", date, event);
        }

        fclose(fp);
}
return 0;
}

This is the file, "Tickler.dat"

150410 DR_APPOINTMENT
150420 MATH_DUE
150426 MEETING
150511 PRINT_HW

Any help would be appreciated.

Upvotes: 1

Views: 349

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

As well as a number of other problems diagnosed in comments and other answers, this line is incorrect:

while(r = fscanf(fp, "%lf %s\n", &date, event) != EOF) {

You need:

while ((r = fscanf(fp, "%lf %s\n", &date, event)) != EOF) {

And the test should really be:

while ((r = fscanf(fp, "%lf %s\n", &date, event)) == 2) {

unless you plan to deal with, for example, an alphabetic character where you were expecting a number (so that r == 0 after the fscanf() returns).

OTOH, since you assign to but don't actually use r, you could simplify the code to:

while (fscanf(fp, "%lf %s\n", &date, event) == 2) {

If you give event a proper size (bigger than 1 which you currently have), then you should write:

char event[32];

while (fscanf(fp, "%lf %31s\n", &date, event) == 2) {

to avoid buffer overflows. Note that there's a difference of 1 in the size specified in the format string and the size declared. Alternatively, on a system that supports POSIX 2008, you could use:

char *event = 0;

while (fscanf(fp, "%lf ^ms\n", &date, &event) == 2) {
    …code using event…
    free(event);
}

The m tells fscanf() to allocate the memory, and the value passed is a char ** as shown. If the scan fails, there is nothing to release.

Upvotes: 1

Angel Angel
Angel Angel

Reputation: 21658

this line int main (int argc, char **argv[]) is correct or

int main (int argc, char **argv) 
int main (int argc, char *argv[])

Upvotes: 2

Related Questions