I have 2 questions. For some reason I am getting a segmentation error and I cant figure out why. I'm new to C programming so it may be obvious but I could not find anything in my program. Here is the code:
Code:
//
// main.c
// head
//
// Created by Bryant Sahota on 7/1/18.
// Copyright © 2018 Bryant S. All rights reserved.
//
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
//If user doesnt specify file name
if(argc == 1)
{
printf("head[OPTION][FILE]\n");
}
//Prints first 10 lines or all of them if fewer than 10
else if(argc == 2)
{
char fileName[100];
strcpy(fileName, argv[2]);
FILE *fPtr;
if ((fPtr = fopen(fileName, "r")) == NULL){
printf("Error! opening file");
}
else
{
printf("in else");
char fileLine[30];
for(int i = 0; i < 10; i++)
{
fgets(fileLine, 30, fPtr);
}
}
}
}
Ignore what is in the nested (second) else statement. Thats my next question. Ive been looking online how to only print the first 5 Lines of a file (or all of them if less) but I cant find anything i can understand. Can anyone push me in the right direction?
this is all that is in the file i'm trying to read from:
hello
world
Red Dead Redemption
cats and dogs
I need to
make the
file a lot longer
but now I’m done
so
I’m
Gonna
Close the file now.