I get this error when trying to run round robin algorithm, and the algorithms are working perfectly fine when taking input from user. this is the code:
else if (select==2)
{
FILE * filehandle;
char lyne[100];
char *item;
int reccount = 0;
// open file
filehandle = fopen("Input_Data1.txt","r");
// Read file line by line
while (fgets(lyne,99,filehandle))
{
numprocess =
printf("%s",lyne);
item = strtok(lyne," ");
p[reccount].arrivetime =atoi(item);
item = strtok(NULL," ");
p[reccount].bursttime =atoi(item);
reccount++;
}
//Close file
fclose(filehandle);
}
The error I get is segmentation fault (core dumped).
screen shot of the input file
I tried reading from a file execting the same result as reading from user input but I got the error showed in the image.
At least these issues:
Avoid atoi(NULL)
item = strtok(lyne," "); may return NULL.
item = strtok(NULL," "); may return NULL.
I suspect the 2nd should be item = strtok(NULL," \n");
NULL == filehandle?
Open may fail.
reccount may exceed max
No need for a -1
// fgets(lyne,99,filehandle)
fgets(lyne, sizeof lyne, filehandle)
FILE * filehandle = fopen("Input_Data1.txt","r");
if (filehandle == NULL) {
fprintf(stderr, "Open failed\n");
return;
}
char lyne[100];
int reccount = 0;
while (reccount < reccount_n && fgets(lyne, sizeof lyne, filehandle)) {
numprocess = printf("%s", lyne); // Unclear how OP is using numprocess
char *item = strtok(lyne," ");
if (item == NULL) {
fprintf(stderr, "strtok(lyne,\" \") failed\n");
return;
}
p[reccount].arrivetime =atoi(item);
item = strtok(NULL," \n");
if (item == NULL) {
fprintf(stderr, "strtok(NULL,\" \n\") failed\n");
return;
}
p[reccount].bursttime =atoi(item);
reccount++;
}
fclose(filehandle);
Related
I have this problem in my c program when I start to reinsert the contents of my file and save a new one. It fails in the while loop and i don't understand why it does that if i have some contents to reinsert from it.
here's my code:
'''
void init(){
char pn[30],pd[30],pp[30];
if ((flptr = fopen("MASTER.dat","r+")) == NULL) {
printf("Couldnt Get Cred");
return;
}
fscanf(flptr,"%s %s %s",pn,pd,pp);
while(!feof(flptr)){
r = (struct Records *) malloc(sizeof(struct Records));
int fr = fscanf(flptr,"%s %s %f",r->PartNum,r->PartDesc, &r->PartPrice);
if(fr == EOF){
printf("HERE");
break;
}
if(head == NULL){
head = r;
}
else{
tail->next = r;
}
tail = r;
}
fclose(flptr);
}
void put(){
if ((flptr = fopen("MASTER.dat","r")) == NULL) {
printf("Couldnt Get Cred");
return;
}
r = head;
fprintf(flptr,"PartNumber PartDescription PartPrice\n");
while (r != NULL){
fprintf(flptr,"%s %s %f\n", r->PartNum, r->PartDesc, r->PartPrice);
r = r->next;
}
fprintf(flptr,"Changes SAVED.");
fclose(flptr);
}
In the function put you open the file to read it, not to write, so your fprintf will have no effect and the file not be even created
if ((flptr = fopen("MASTER.dat","r")) == NULL) {
must be
if ((flptr = fopen("MASTER.dat","w")) == NULL) {
If later you try to read that non existing file with init you will not success
Out of that put and init use the global variable r and modify it, I encourage you to use a local variable to avoid possible problems
Why do you open file file with "r+" in init while you only read it ?
When you read string through (f)scanf I encourage you to limit the length to not write out of the receiver with an undefined behavior, and to always check the result, so for instance replace
fscanf(flptr,"%s %s %s",pn,pd,pp);
by
if (fscanf(flptr,"%29s %29s %29s",pn,pd,pp) != 3) {
printf("invalid file contain\n");
return;
}
I am trying to read a file in C and then store values after a certain word is read. For example, in my input.txt file, the following are the contents:
GREETINGS
Hello 13
Namaste 24
Hola 36
FLAVORS
Vanilla 23
Chocolate 78
I want to read past GREETINGS and then store Hello and its value 13 then Namaste and its value 24, etc. And then read past FLAVORS and store Vanilla and its value 23, etc. And so on...
I know how to open a file but not sure how to proceed from there.
void readInput() {
char input_file[100];
FILE *fp;
printf("Please enter the name of the file you would like to read: \n");
scanf("%s", input_file);
printf("You entered: %s\n", input_file);
fp = fopen(input_file, "r");
if (fp == NULL) {
printf("File does not exist.\n");
exit(1);
}
else
printf("This file exists!\n");
}
From your sample data it is not clear whether the lines with data have the always the same format. So I
suggest that you store in a variable the current mode (that means GREETINGS, FLAVOR, etc) and you call
a specific parsing function for every mode depending of the value of the current
mode.
I'd create this enum first
typedef enum {
MODE_GREETINGS = 0, // <-- important that this value is 0
MODE_FLAVORS,
...
MODE_INVALID
} Modes;
and a variable (this can be a global variable) with all modes:
const char *modes_lookup[] = {
"GREETINGS",
"FLAVORS",
...
};
Then I'd write a function that returns the mode:
Modes get_mode(const char *src)
{
if(src == NULL)
return MODE_INVALID;
for(size_t i = 0; i < sizeof modes_lookup / sizeof modes_lookup[0]; ++i)
{
if(strcmp(src, modes_lookup[i]) == 0)
return i;
}
return MODE_INVALID;
}
Now you can parse the file like this:
char line[1024];
Modes mode = MODE_INVALID;
size_t lineno = 0;
while(fgets(line, sizeof line, fp))
{
lineno++;
// removing newline
line[strcspn(line, "\n")] = 0;
Modes newmode = get_mode(line);
// check if line is a GREETINGS, FLAVOR, etc line
if(newmode != MODE_INVALID)
{
// sets the new mode and continue with the next line
mode = newmode;
continue;
}
// parsing depending on the current mode
if(mode == MODE_GREETINGS)
{
if(parse_greetings(line) == 0)
{
fprintf(stderr, "Cannot parse data on line %zu\n", lineno);
break;
}
continue;
}
if(mode == MODE_FLAVORS) {
if(parse_flavor(line) == 0)
{
fprintf(stderr, "Cannot parse data on line %zu\n", lineno);
break;
}
continue;
}
// more (if mode == MODE_xxx) cases as needed
if(mode == MODE_INVALID)
{
// mode == MODE_INVALID
fprintf(stderr, "File does not start with a mode line.\n");
break;
}
}
Then you've got to write the parse_greetings, parse_flavor, parse_xxx functions. Like I said
before, it's not clear from your sample whether the format will be always the
same, so it depends on the format whether you use strtok or sscanf. Also
your description of how and where you want to store the values is very vague, so
I don't know what would be the best for your.
The easiest would be sscanf and if the data line gets more complex, you can then
use strtok.
For example with sscanf
int parse_greetings(const char *line)
{
if(line == NULL)
return 0;
char name[20];
int val;
if(sscanf(line, "%19s %d", name, val) != 2)
return 0;
// do whatever you need with 'name' and 'val'
return 1;
}
And with strtok:
int parse_greetings(char *line)
{
if(line == NULL)
return 0;
char name[20];
int val;
const char *delim = " \t\r\n";
char *token = strtok(line, NULL);
// line has only delimiters
if(token == NULL)
return 0;
strncpy(name, token, sizeof name / sizeof name[0]);
name[(sizeof name / sizeof name[0]) - 1] = 0;
token = strtok(NULL, delim);
if(token == NULL)
return 0;
char *end;
val = strtol(token, &end, 0);
// check if token is a number
if(*end != '\0')
return 0;
// do whatever you need with 'name' and 'val'
return 1;
}
I'm not sure what exact criteria you're using to choose which lines to skip, but the next step for reading lines is to use fscanf or fgets. This tutorial should help you get started with reading files in C.
Edit, to make this more relevant after your comment:
fgets may be a better choice. You'll need to read each line, then loop through each character, to check if they are all uppercase.
If they are not uppercase, you can use fscanf, using the format %s %d, to scan the data line.
I have a two filepaths input by the user and stored in an array. However, when I try to use one of these filepaths to open a file using fopen the code exits as if the file does not exist. If I hard code the filepath into the fopen function eveything proceeds perfectly.
For Example:
//Libraries
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
//Global Functions
//Main Function
int main()
{
//Local Variables
char * user_input_full = NULL;
char user_input = 'a';
size_t len = 0; //Pointer for user_input_full
int size = 0; //Length of the input_use_full array
char *input_array[2]; //This hold the filepaths
int i=0; //A loop counter
//Carve out an initial array for the use input string (it is of unknown length)
user_input_full = calloc(16,sizeof(char));
size = 16;
//Take user input until a newline is encountered.
while(user_input != '\n')
{
scanf("%c", &user_input);
user_input_full[len] = user_input;
len = len+1;
if(len==size)
{
#ifdef DEBUG_MODE
printf("The input stream is being reallocated\n");
#endif
user_input_full = realloc(user_input_full,sizeof(char)*(size+16));
if(user_input_full == NULL)
{
//realloc failed, return a fail status
printf("Realloc of the input stream failed.\n");
return EXIT_FAILURE;
}
}
}
user_input_full[len] = '\0';
#ifdef DEBUG_MODE
printf("The user input was: %s \n", user_input_full);
#endif
//Parse out the file streams
input_array[i] = strtok(user_input_full," ");
while(input_array[i]!=NULL)
{
input_array[++i] = strtok(NULL," ");
}
#ifdef DEBUG_MODE
printf("Input array Values:\n");
for (i=0;i<2;i++)
{
printf("%s \n",input_array[i]);
}
#endif
//open the file specified in input_array[0]
if(fopen(input_array[0],"r") == NULL)
{
printf("Open of the input file failed.\n");
printf("Tried to open: %s ", input_array[0]);
return EXIT_FAILURE;
}
else
{
printf("The file opened.\n");
}
return EXIT_SUCCESS;
}
Would print the error block. However:
//Open the file specified in array[0]
if(fopen("test.txt","r") == NULL)
{
printf("Failed to open the input file.\n");
return EXIT_FAILURE;
}
else
{
printf("The file opened.\n");
}
Works perfectly fine.
I also tried passing the value in input_array[0] to a const char*, but that did not work either. I feel like I am missing some fundamental concept here.
EDIT: Clarified one of the comments in the code block
The real reason it is failing is due to trailing newline in the filename. All you need is to add newline as string token.
Change this line:
input_array[i] = strtok(user_input_full," ");
to:
input_array[i] = strtok(user_input_full," \n");
and this line:
input_array[++i] = strtok(NULL," ");
to:
input_array[++i] = strtok(NULL," \n");
This will remove the trailing newlines.
First mistake I note is in the following code block. it's inputing 3 three strings to input_array and going out of bound.
//Parse out the file streams
input_array[i] = strtok(user_input_full," ");
while(input_array[i]!=NULL)
{
input_array[++i] = strtok(NULL," ");
}
Change this code block to something as shown here.
input_array[i] = strtok(user_input_full," ");
for(i=1;i<2;i++)
{
input_array[i] = strtok(NULL," ");
}
The following function is only used to display certain areas of a file. In this case I am trying to copy every line that has the word "EMPTY" from the main file to another file. Other than by opening a file to write to I use for char arrays to look for the proper string needed. At this point, I try to use the data from that file(In which the string was searched for) and try to copy it into another file. At this point some of the new file prints to the screen which is the first part at the top under where I created the file but when I try to add the string from the other file they do no print. Can you print certain string fro one file to another?
void emptySeats(void)
{
int position = 0;
int AvalabileOne = 0;
int countGone = 0;
int confirm = 0;
char testOne[] = "EMPTY";
char StrOne[10], StrTwo[10], StrThree[10], StrFour[10];
FILE *fEmptyseatArrangement;
fEmptyseatArrangement = fopen("airlineEmptySeatingArrangment.txt", "w+");
fprintf(fseatArrangement, "\t\t\tEcono-Airlines Passangers System\n\n\t Seat Number\t Seatavalability Last Name First Name\n");
do
{
fseatArrangement = fopen("airlineSeatingArrangment.txt", "r");
fseek(fseatArrangement, 102, SEEK_SET);
while (AvalabileOne < FULL)
{
fscanf(fseatArrangement, "%s%s%s%s\n", &StrOne, &StrTwo, &StrThree, &StrFour);
if (strcmp(StrThree, testOne))
{
fprintf(fEmptyseatArrangement, "\t\t%s\t\t%s\t\t%s\t\t%s\n", StrOne, StrTwo, StrThree, StrFour);
countGone = countGone + 1;
}
AvalabileOne = AvalabileOne + 1;
}
fclose(fEmptyseatArrangement);
fclose(fseatArrangement);
fEmptyseatArrangement = fopen("airlineEmptySeatingArrangment.txt", "r");
while (fgets(econoAirEmptySeatArrangement, 1000, fEmptyseatArrangement) != NULL)
printf("%s", econoAirEmptySeatArrangement);
fclose(fEmptyseatArrangement);
printf("There are %d seats vacant at the moment\n", FULL - countGone);
printf("Enter Zero(0) Key to return to menu at anytime.");
scanf(" %d", &position);
if (position == 0)
{
system("cls");
menu();
}
else
{
system("cls");
printf("INVALID INPUT! Please try again.\n");
}
} while (AvalabileOne != 0);
system("pause");
return;
}
So here's my code for my main()
int main(int argc, char **argv) {
if (argc != 3) {
puts("Invalid number of args in the input. Sorry.");
return 0;
}
if (doesItExist(argv[2]) == 0) {
return 0;
}
FILE *fpoint;
char yesorno[2];
tail = (WordN) malloc(sizeof(struct WordNode));
tail->word = "";
tail->first = (FileN) malloc(sizeof(struct FileNode));
(tail->first)->freq = -1;
ftw(argv[2], tokeForMe, 1);
/**
fpoint = fopen(argv[1], "r");
if(fpoint != NULL) { // file exists give user option to overwrite or rename
getInput("Do you want to overwrite the file? Enter only either Y or N nothing else\n", yesorno, 2);
if(yesorno[0] == 'N' || yesorno[0] == 'n') {
puts("All right. Not going to proceed with the program");
return 0;
}
else if(yesorno[0] != 'Y' && yesorno[0] != 'y') {
puts("You inputted some other character, try again \n");
getInput("Do you want to overwrite the file? Enter Y or N. Do not enter anything other than 1 Y or 1 N \n", yesorno, 2);
}
}
fclose(fpoint);
**/
FILE *index;
index = fopen(argv[1], "w");
//puts("here");
writeToIndex(index, tail->next); //tail is pointing to the first word node
puts("there");
if (doesItExist(argv[1]) == 0) {
return 0;
}
fclose(index);
TailTerminate();
return 0;
}
The code seg faults when I uncomment the part when I make a file pointer to read argv[1] to find out whether the user wants to overwrite the file specified in argv[1].
The program itself is just a program that makes a sort of indexer out of a directory of files and then prints it out. The directory path is specified in argv[2] and the path to print out the index is specified in argv[1].
Can someone help me with this? The rest of the program (the Tail nodes and such) are only to make a sort of list the words and frequencies that appear in the program.
You don't show all the functions called from main (getInput?), and they may content errors. From your commented code, I can only say that you wrote something like this:
FILE *f = fopen(...);
if (f != NULL)
{
/* use f */
}
fclose(f);
But it should be like this:
FILE *f = fopen(...);
if (f != NULL)
{
/* use f */
fclose(f);
}
That is, do not call fclose() with a NULL pointer.