File manipulation

Hi guys, sorry to bother but I am having a bit of trouble with this question, I'm very new to file manipulation so there is probably a lot of mistakes in the coding, however I gave it my best and when I compile, for example "./head 1000.txt" (which I wrote to have the numbers 1 - 1000 in), I get "Segmentation fault", yet when I compile "./head -n 3 1000.txt" it prints "1000" and then "Segmentation fault" on a new line, I'm quite confused and need help.
Anyway, thanks for your help.

"Write a program, head.c, which given a single argument n prints the first 10 lines of the file. If the file has less than 10 lines the entire file should be printed.
It should also be possible to specify that a different number of lines be printed. This will specified by passing the string "-n" as the first argument to the program, the number of lines to be printed as the second argument and the file as the third argument. "

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#define CHAR 1024

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

    int i;
    FILE *pFile;
    char string[CHAR];
    int c = atoi(argv[2]);
    
    if(argc<3){
        pFile = fopen(argv[1], "r");
        if(pFile == NULL){
            printf("Could not open the file.\n");
            return 0;
        }else{
            for(i=0;i<10;i++){
                 fgets(string, CHAR, pFile);
                 printf("%s\n", string);
                 pFile++;
            }
        }
    }else{
        pFile = fopen(argv[3], "r");
        if(pFile == NULL){
            printf("Could not open the file.\n");
            return 0;
        }else{
            for(i=0;i<c;i++){
                fgets(string, CHAR, pFile);
                printf("%s\n", string);
                pFile++;
            }
        }
        fclose(pFile);
    }
    return 0;
}
int c = atoi(argv[2]);if you pass less than 2 parameters it is instant segfault.
pFile++; You are increasing pointer and making it invalid. Next operation will lead to crash
Last edited on
Thanks a lot that fixed the Segmentation Fault problem, now it prints SOME of the desired output, however, every single output STARTS with "1000" and then "0" and then what I want, I have no idea why this is the case.
Last edited on
Either you fixed something wrong or there is something with file
Could you show the current version of the code?
Thanks for the help but I just figured out the problem, the file I was getting the output from had "1000" and "0" at the start before the 1 - 1000 began, so sorry for taking your time and I am grateful for the help <3
Topic archived. No new replies allowed.