0
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>

char date[35] = {"0"};

void main()
{
        FILE *fp;
        char ch;
        int i=0;

        if(fork() == 0)
        {
                system("date '+%Y-%m-%d %H:%M:%S' > date.txt");
                exit(0);
        }
        wait(0);

        fp = fopen("date.txt","w+");
        if(fp == 0) {return;}

        while((ch = fgetc(fp)) != EOF)
        {
                date[i++] = (char)ch;
        }
        fclose(fp);
        date[i] = '\0';

        printf("date = %s", date);
}

I keep on getting segmentation fault in this code. I have even tried creating the file named "date.txt" manually.

The command date '+%Y-%m-%d %H:%M:%S' > date.txt works on bash separately well.

Can someone please help me find, what am I doing wrong?

[update:] Forgot to initialize i = 0. Edited but still the segment violation persists.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Doherty
  • 85
  • 1
  • 8

3 Answers3

1

You are using a char value to check against EOF, but since EOF is a numeric value, ch will never be equal to EOF. This means that your loop will run forever, overrunning your array, which only has 35 elements. You have to use int ch instead.

hat
  • 781
  • 2
  • 14
  • 25
0

You should to initial variable i or it gets a random value.

void main()
{
    FILE *fp;
    char ch;
    int i = 0;
...
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

The statement overflowed the max size of 35. That means i become greater than 0..34.

date[i++] = (char)ch;
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29