I got segmentation fault ( core dumped) in c while reading a file.i used this code for milion other files and it workes fine. But this file has 138 lines when others start at 250. So im guessing thats the problem? (the code is on the bottom of my post)its suppose to help me work on the read data so i could do operations on them in the code but whatever i do its just "core dumped"
it breaks here :
while (fgets(line, sizeof line, fp) != NULL) {
strtok(line, "\n");
parseLine(line, &dataList);
}
i already tried :
char *line = malloc( sizeof(char) * ( LINE_BUFFER + 1 )
instead of
char line[LINE_BUFFER];
Heres the part of the code that reads a file :
#define DIFF_BUFFER 99999999
DataLineNode *loadData(const char *fileName) {
FILE *fp;
char line[LINE_BUFFER];
DataLineNode *dataList = NULL;
fp = fopen(fileName, "r");
if (fp == NULL) {
printf("No file '%s'.\n", fileName);
exit(EXIT_FAILURE);
}
while (fgets(line, sizeof line, fp) != NULL) {
strtok(line, "\n");
parseLine(line, &dataList);
}
fclose(fp);
return dataList;
}
````
Related
my code keeps throwing a segmentation fault from internal c libraries, my code is the following:
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r");
if(shaderFile)
{
//TODO: load file
for (char *line; !feof(shaderFile);)
{
fgets(line, 1024, shaderFile);
strcat(vertexShaderCode, line);
}
it is meant to load all the data from a file as a c string, line by line. can anyone help?
You want this:
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r");
if (shaderFile == NULL)
{
printf("Could not open file, bye.");
exit(1);
}
char line[1024];
while (fgets(line, sizeof(line), shaderFile) != NULL)
{
strcat(vertexShaderCode, line);
}
You still need to make your that there is no buffer overflow. Possibly you need touse realloc in order to expand the buffer if the initial length of the buffer is too small. I leave this as an exercise to you.
Your wrong code:
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r"); // no check if fopen fails
for (char *line; !feof(shaderFile);) // wrong usage of feof
{ // line is not initialized
// that's the main problem
fgets(line, 1024, shaderFile);
strcat(vertexShaderCode, line); // no check if buffer overflows
}
FILE *fp;
fp = fopen(filen, "wb");
const char tok[2] = ",";
char str[340];
while (fgets(str, 340, stdin) != NULL)
{
struct test loadTest;
printf("You entered: %s", str);
strncpy(loadTest.level, strtok(str, tok), 20);
strncpy(loadTest.first, strtok(NULL, tok), 30);
fwrite(&loadTest, sizeof(struct test), 1, fp);
}
fclose(fp);
Hello all,
For some reason I'm getting a segmentation fault error in my code.
I'm almost positive the error is somewhere within the small code block above (since that's all I modified for the seg fault), but I can't seem to pinpoint it.
I know segmentation faults have to do with accessing memory I shouldn't be accessing, but I'm not sure where I am even doing that in the code.
Any help would be greatly appreciated!
Some improvements of your code
check result of fopen before read/write to file
initialize variables before using their values
use sizeof instead of constant (as mentioned in comments)
strtok() can return NULL and this must be checked (see here why)
you must use strncpy() carefully because of this
Here is corrected version of your code
FILE *fp;
fp = fopen(filen, "wb");
if (fp == NULL)
{
printf("Error opening file: %s", filen);
}
else
{
const char tok[2] = ",";
char str[340];
while (fgets(str, sizeof(str), stdin) != NULL)
{
struct test loadTest;
char *level;
char *first;
memset(&loadTest, 0, sizeof(loadTest));
printf("You entered: %s", str);
level = strtok(str, tok);
if (level == NULL)
{
continue; // bad input ?
}
first = strtok(NULL, tok);
if (first == NULL)
{
continue;
}
strncpy(loadTest.level, level, sizeof(loadTest.level)-sizeof(char));
strncpy(loadTest.first, first, sizeof(loadTest.first)-sizeof(char));
fwrite(&loadTest, sizeof(loadTest), 1, fp);
}
fclose(fp);
}
I have a function which open a file, read its content line by line and then push it to an array. I have managed to get the array functionnal inside the right function, but when I want to get it back to my main function, I cannot get any items of my array.
Some code will help you to understand:
My main function:
/* ----------------- MAIN ------------ */
int main(int argc, char *argv[]) {
/*... some useless code for now ... */
char **ptrLines = NULL;
ptrLines = readEventFile(ptrParam, ptrLines);
outputExecTrace(WAR, "PTRLINES x : %x", ptrLines);
outputExecTrace(WAR, "PTRLINES char[] : %s", *(ptrLines + 2));
return EXIT_SUCCESS;
}
My fileReader function:
char** readEventFile(Parameters *parameters, char **arrLine) {
FILE *fp = fopen(parameters->inputFilePath, "r");
if (fp == NULL)
exit(0);
char line[128];
int nbCharOfLine = 0;
while(1) {
fgets(line, sizeof(line), fp);
if (feof(fp))
break;
nbCharOfLine++;
}
fclose(fp);
arrLine = malloc(sizeof(line) * nbCharOfLine);
nbCharOfLine = 0;
fp = fopen(parameters->inputFilePath, "r");
while(1) {
fgets(line, sizeof(line), fp);
if (line[0] != '#') {
arrLine[nbCharOfLine] = malloc((strlen(line)+1) * sizeof(char));
strcpy(arrLine[nbCharOfLine], line);
nbCharOfLine++;
}
if (feof(fp))
break;
}
fclose(fp);
outputExecTrace(WAR, "ARRLINE x : %x", arrLine);
outputExecTrace(WAR, "ARRLINE char[] : %s", *(arrLine + 2));
return arrLine;
}
Has it is, my outputs are the followings:
WARNING: ARRLINE int : -2020552688
WARNING: ARRLINE char[] : 1 3 4 //This is the result I am looking for.
WARNING: PTRLINES int : -2020552688 // Same as ARRLINE
Segmentation fault (core dumped) // And this is because ptrLines[2] doesn't contains anything... but why ?!
How can I fix this ?
It's hard to tell exactly what happen, because you have several small problems within code, which could lead to this, try to change your code in following way:
char** readEventFile(char* fileName) {
char line[128];
int nbCharOfLine = 0;
FILE *fp = fopen(fileName, "r");
if (fp == NULL)
exit(1);
while (!feof(fp)) {
char *r = fgets(line, sizeof(line), fp); // NOTE: proper handling of fgets return value
if ((r != NULL) && (line[0] != '#'))
nbCharOfLine++;
}
fclose(fp);
char **arrLine = calloc(nbCharOfLine, sizeof(char*)); // use calloc to be sure
nbCharOfLine = 0;
fp = fopen(fileName, "r");
while (!feof(fp)) {
char *r = fgets(line, sizeof(line), fp);
if ((r != NULL) && (line[0] != '#')) {
arrLine[nbCharOfLine] = calloc(strlen(line) + 1, sizeof(char));
strcpy(arrLine[nbCharOfLine++], line);
}
}
fclose(fp);
return arrLine;
}
in your main, you will call this function like:
char **ptrLines = readEventFile(ptrParam->inputFilePath);
Not so sure this is the whole problem, but the posted code:
while(1) {
fgets(line, sizeof(line), fp);
if (line[0] != '#') {
arrLine[nbCharOfLine] = malloc((strlen(line)+1) * sizeof(char));
strcpy(arrLine[nbCharOfLine], line);
nbCharOfLine++;
}
if (feof(fp))
break;
}
is not the right approach for several reasons,
including that function feof()
is only asserted 'true' when the code has tried to read past the
end of the file.
suggest:
while( fgets(line, sizeof(line), fp) )
{
if (line[0] != '#')
{
if( NULL == (arrLine[nbCharOfLine] = malloc((strlen(line)+1) * sizeof(char)) ) )
{ // then, malloc failed
perror( "malloc failed" );
// close file and free all malloc'd areas
exit( EXIT_FAILURE );
}
// implied else, malloc successful
strcpy(arrLine[nbCharOfLine], line);
nbCharOfLine++;
}
}
My code compiles just fine but when I run it I get bus error: 10
void backupf(char *namelist, char *dirname)
{
char *in_filename;
char *out_filename;
char line[MAXPATHLEN];
FILE *filenames = fopen(namelist, "r");
if(filenames == NULL)
{
fprintf(stderr, "Cannot Open File\n");
exit(EXIT_FAILURE);
}
while( fgets(line, sizeof line, filenames) != NULL )
{
sprintf(in_filename, "./%s\n", line);
sprintf(out_filename, "%s/%s\n", dirname, line);
}
backup(dirname, in_filename, out_filename);
fclose(filenames);
}
It's supposed to take a text file argument with a list of file names and then use that information to back it up to a backup directory using a backup function I've written.
You don't allocate space for the file names; you should. You're writing over indeterminate memory. This would probably work better:
void backupf(char *namelist, char *dirname)
{
char in_filename[MAXPATHLEN];
char out_filename[MAXPATHLEN];
char line[MAXPATHLEN];
FILE *filenames = fopen(namelist, "r");
if (filenames == NULL)
{
fprintf(stderr, "Cannot Open File\n");
exit(EXIT_FAILURE);
}
while (fgets(line, sizeof(line), filenames) != NULL)
{
snprintf(in_filename, sizeof(in_filename)"./%s\n", line);
snprintf(out_filename, sizeof(out_filename), "%s/%s\n", dirname, line);
backup(dirname, in_filename, out_filename);
}
fclose(filenames);
}
I am trying to write a C code under UNIX to read the third word from each line of a text, and store it to a string by using POPEN. However my code is giving me an error (Modifiable lvalue required for assignment operator) at the line inside my while loop. Here is my code:
int main() {
int license = 0;
char number[100];
FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");
if ( file != NULL)
{
char line [128];
while (fgets(line, sizeof line, file) != NULL)
{
number = popen("cut -f3 -d' '", "r");
}
fclose (file);
printf("Hello %s\n", number);
}
I know there are a few errors on here as i am still kinda new to C. But please help me correct them, thanks!
FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");
This will run a grep command looking for User and redirect the output to the file filename. It will return a FILE * that allows you to read the output of this command, but as that output has been redirected, you won't get anything.
popen("cut -f3 -d' '", "r");
This will run the cut command which, as it has no file arguments, will read from stdin and write to stdout which can be read by the FILE * that popen returns, but which you aren't doing anything with.
You probably want something more like:
char line[128];
int number;
FILE *file = popen("grep User results_today.TXT_05012013 | cut -f3 -d' '", "r");
if (file) {
while (fgets(line, sizeof line, file)) {
if (sscanf(line, "%d", &number) == 1) {
printf("It's a number: %d\n", number);
}
}
pclose(file);
}
You assign the result of popen to a fixed size char array. This is not possible.
number = popen("cut -f3 -d' '", "r");
Do it like the first popen -> assign it to FILE *file2
First of I'm not a C programmer
This is my implementation (with a lot of borrowed lines of course ;) ).
I was just fed up of
popen
while fgets
printf // I want to store in char* got it?
So here's the code. It may not be perfect but does the job :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concatenate(char * dest, char * source) {
char * out = (char *)malloc(strlen(source) + strlen(dest) + 1);
if (out != NULL) {
strcat(out, dest);
strcat(out, source);
}
return out;
}
char * executeCmd(char * cmd) {
FILE *fp;
int BUFF_SIZE = 1024;
int size_line;
char line[BUFF_SIZE];
char* results = (char*) malloc(BUFF_SIZE * sizeof(char));
if (cmd != NULL) {
/* Open the command for reading. */
fp = popen(cmd, "r");
if (fp != NULL) {
/* Read the output a line at a time - output it. */
while (fgets(line, size_line = sizeof(line), fp) != NULL) {
results = concatenate(results, line);
}
}
/* close */
pclose(fp);
} // END if cmd ! null
return results;
}
int main( int argc, char *argv[] ) {
char * out = executeCmd("ls -l");
printf("%s\n", out);
return 0;
}