FILE pointer is expired without rhyme or reason - c

I have this problem after I add some socket connection codes after following codes. What could be a reason when fp is ok, pointing some memory address, while reading the data (line 4), but when debugger(gdb) reaches the if block, fp pointer is just pointing 0x0.
#define CHANNELS_PER_IOM 25
...
int OldValues[CHANNELS_PER_IOM];
FILE * fp;
FILE * fp_t;
int buff;
int i;
fp = fopen("/windcom/tmp/dout_values", "r");
fp_t = fopen("/windcom/tmp/dout_values.tmp", "w");
i = 0;
while(fp && fscanf(fp, "%d\n", &buff) == 1) // fp is pointing some address here.
{
i++;
OldValues[i-1] = buff;
//printf("%d %d \n", OldValues[i-1], buff);
}
if(!fp) //fp is pointing 0x0 here.
{
for(i=0; i<CHANNELS_PER_IOM; i++)
{
OldValues[i] = 0;
}
}

Where is OldValues defined? You have probably not large enough and unfortunately the fp is getting overwritten inadvertently.
EDIT
Try this code:
while(i < CHANNELS_PER_IOM &&
fp &&
fscanf(fp, "%d\n", &OldValues[i++]) == 1) // fp is pointing some address here.
{
// Empty
}
EDIT 2
Put
And after
fp = fopen("/windcom/tmp/dout_values", "r");
put
if (!fp) printf("Unable to open file\n");
and this will check if the file is actually opened.

Related

Cant write a 2d array on a FILE on C

char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
FILE *f;
f= fopen( "TIMES.txt", "wb");
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<7;j++)
{
printf("%c",arrTypeLabels[i][j]);
fwrite(arrTypeLabels[i][j],sizeof(char),sizeof(arrTypeLabels),f);
}
}
fclose(f);aenter code here
Im opening the TIMES.txt file but i cant see any output, althought i think my code is right .......................... :/ pls help...
char arrTypeLabels[3][7] = {
{"Random"},
{"ASC"},
{"DESC"}
};
FILE *f = fopen("TIMES.txt", "wb"); //wb is OK
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 7; j++)
{
printf("%c", arrTypeLabels[i][j]);
fwrite(arrTypeLabels[i] + j, sizeof (char), sizeof (char), f); //your mistake is here
}
}
fclose(f);
I don't know how you're even able to copile your code, because in fwrite, the first argument needs to be a pointer, or in your code, you're giving the value.
Also, what you're trying to do is confusing, because it looks like you're trying to write char by char, but you're attempting to write the whole data contained in arrTypeLabels in one fwrite call.
If you just want to write that array to a file, you can make something like :
char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
FILE *f;
f= fopen( "TIMES.txt", "wb");
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fwrite(arrTypeLabels,sizeof(char),sizeof(arrTypeLabels),f);
fclose(f);
or something like :
char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
FILE *f;
f= fopen( "TIMES.txt", "wb");
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 7; j++)
fwrite(arrTypeLabels[i] + j,sizeof(char),sizeof(char),f);
}
fclose(f);
note that the first method is much faster since you don't have to write (to a file i.e into the hard drive) every single character one at a time.
fwrite first and third parameters are wrong. Since you want to write char by char, your line should be fwrite(&buf[i][j], 1,1,f);
Or simplier, use fputc:
fputc(buf[i][j], f);

CS50 recover doesn't output any images

I'm working on the recover program of the CS50 course. Here are the instructions:
Implement your program in a file called recover.c in a directory called recover.
Your program should accept exactly one command-line argument, the name of a forensic image from which to recover JPEGs.
If your program is not executed with exactly one command-line argument, it should remind the user of correct usage, and main should
return 1.
If the forensic image cannot be opened for reading, your program should inform the user as much, and main should return 1.
Your program, if it uses malloc, must not leak any memory.
I think my code is supposed to work, but it doesn't. In fact, it doesn't output any images at all! Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * pFile = NULL;
unsigned char *buffer = malloc(512);
char* filename = NULL;
int filenumber = 0;
//If user didn't print 2 items
if(argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//Open the file
pFile = fopen(argv[1], "r");
if (!pFile)
{
fprintf(stderr, "File cannot be opened\n");
return 2;
}
int j=0;
// checking the card by 512b chunks
//loop (i=0, i++);
while (pFile)
{
int i =0;
i++;
//k=fread (buffer, 512, i, *file);
int k = fread(buffer, 512, i, pFile);
// if 512 byte block is jpeg, make new jpeg file
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// if it's not the first file, we should close the last one
if (filename != NULL)
{
fclose(pFile);
}
//sprintf
sprintf(filename, "%03i.jpg", 2);
//FILE = fopen (W)
pFile = fopen(filename, "w");
// fwrite (buffer, 512, j, *file1)
fwrite (buffer, 512, j, pFile);
//j=j+1
j = j + 1;
}
// if k<512 - end of the loop
if (k < 512)
{
return 0;
}
}
free(buffer);
}
I don't understand it, but I see no new files or JPEGs pop-up in my files. When I try to double-click on the file, which is called card.raw, it doesn't let me open it.
You have a load of problems. Running your code in a debugger should reveal most of them within a second.
Let's take a look:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * pFile = NULL;
unsigned char *buffer = malloc(512);
char* filename = NULL; <<==== You never allocate any memory for this. Use an array.
int filenumber = 0;
//If user didn't print 2 items
if(argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//Open the file
pFile = fopen(argv[1], "r");
if (!pFile)
{
fprintf(stderr, "File cannot be opened\n");
return 2;
}
int j=0;
// checking the card by 512b chunks
//loop (i=0, i++); <<== No information provided by this comment.
while (pFile) <<== pFile is your input file. This should never change. ???
{
int i =0;
i++;
//k=fread (buffer, 512, i, *file); <<== Useless comment. Nearly same as code below but causes compiler error
int k = fread(buffer, 512, i, pFile); <<== i is always 1 and must be 1. Don't use variable.
<<== BTW: You should check k **before** using the buffer.
// if 512 byte block is jpeg, make new jpeg file
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// if it's not the first file, we should close the last one
if (filename != NULL)
{
fclose(pFile); <<== Yikes!!! This is your input file.
}
//sprintf <<== Yes, that's obvious. Useless comment.
sprintf(filename, "%03i.jpg", 2); <<== Yikes!! You never allocate memory. NULL pointer!!
<<== Why do you always print 2? you have a counter.
//FILE = fopen (W) <<== Again no useful information in comment
pFile = fopen(filename, "w"); <<== Feed NULL into fopen and kill pFile.
// fwrite (buffer, 512, j, *file1) <<== you know what I mean...
fwrite (buffer, 512, j, pFile); <<== You only have 1 buffer, why write j blocks?
//j=j+1 <<== obvious
j = j + 1;
}
// if k<512 - end of the loop
if (k < 512) <<== fread returns number of elements, i.e. 1, not number of bytes.
{
<< you return without
- closing files
- freeing buffer
return 0;
}
<<== Now you go back to top of the loop and want to read next block from your raw file but pFile was killed in the loop.
}
free(buffer);
}

Read a file containing an array of long in C

I am trying to get the data from an array of longs that I have just created but I got different data.
please see code below :
#include <string.h>
#include "readfile.h"
int main()
{
long wr_data [6] ;
wr_data[0] = 11;
wr_data[1] = 1100;
wr_data[2] = 1122323;
wr_data[3] = 11333;
wr_data[4] = 11434243;
wr_data[5] = 1166587;
writeFile(wr_data);
readFile();
return(0);
}
int readFile()
{
FILE *file;
long * data
printf("Error Reading File\n");;
/* Open file for both reading and writing */
file = fopen(fileName, "r");
if (file == NULL)
{
printf("Error Reading File\n");
return -1;
}
for (int i = 0; i < 5; i++)
{
fscanf(file, "%ld", &data[i] );
printf("data[%d]: %ld \n",i, data[i]);
}
fclose(file);
return 0;
}
int writeFile(long * data)
{
FILE *fp;
if (data != NULL)
{
if ((fp = fopen(fileName,"w")) == NULL)
return -1;
if (*data !=0 )
fwrite(data,sizeof(long),6,fp);
printf("Write data\n");
fclose(fp);
}
return 0;
}
the result I get is as follows :
Write data
data[0]: 140526045102081
data[1]: 47
data[2]: 197764
data[3]: 140526045102080
data[4]: 4096
I want to preserve the write function as it is as it comes from an existing code. I tried also the function fread but without success
fread(data, sizeof(long ), 6, file);
Thanks in advance for help.
It's working here. I made the following changes to your code:
//needed for malloc
#include <stdio.h>
//needed for output
#include <stdlib.h>
...
char *fileName = "so";
...
//allocate memory to store the values
long *data = (long *)malloc(sizeof(long)*6);
...
//read the stored longs
fread(data, sizeof(long ), 6, file);
int i;
for(i=0; i<6; i++)
printf("%ld\n", data[i]);
what do you think?
edit:
Well the main change was the memory allocation. When you want to store values of any kind, your program needs to be granted by the operating system a memory zone to store those values.
In this case we had two options, either create a staticly allocated array with a fixed size, or allocate the needed memory in a dynamic fashion with the malloc function or equivalent.
Don't forget, if you want to store something, first make sure you have a place for it to be stored (i.e. allocated memory). If you don't you will most likely get an error "Segmentation Fault" aka "SIGSEGV" which means that you tried to access memory that didn't belong to you.
Also, the "fscanf(file, "%ld", &data[i] );" will read "file" as text and will try to parse floats out of that same text. Since you're storing the longs as longs and not as text, this will not work, since you're writing and reading different things.
You are writing the binary content of the array to the file and afterwards try to interpret this as a long value which can obviously not work. If you want to store the numbers as text you must convert them to text before writing or print them to file by using the fprintf(FILE *, const char *, ...) function.
It is working as expected using the following code using a text file (you might want to change the filename). Otherwise you could just fwrite and fread the whole content, depending on your needs.
#include <stdio.h>
const char *filename = "yourfile";
int readFile()
{
FILE *file;
long data[6];
int i;
printf("Error Reading File\n");;
/* Open file for both reading and writing */
file = fopen(filename, "r");
if (file == NULL)
{
printf("Error Reading File\n");
return -1;
}
for (i = 0; i < 6; i++)
{
fscanf(file, "%ld", &data[i] );
printf("data[%d]: %ld \n",i, data[i]);
}
fclose(file);
return 0;
}
int writeFile(long * data)
{
FILE *fp;
int i;
if (data != NULL)
{
if ((fp = fopen(filename,"w")) == NULL)
return -1;
if (*data !=0 )
{
for(i = 0; i != 6; ++i)
fprintf(fp, "%ld ", data[i]);
}
printf("Write data\n");
fclose(fp);
}
return 0;
}
int main()
{
long wr_data [6] ;
wr_data[0] = 11;
wr_data[1] = 1100;
wr_data[2] = 1122323;
wr_data[3] = 11333;
wr_data[4] = 11434243;
wr_data[5] = 1166587;
writeFile(wr_data);
readFile();
return(0);
}

C File Reader from array

I can see the last printf output of y but the fpc turns null.
I suspected for double quotes in fopen function but not could not find a solution: how to fix it?
Part of the code ;
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST %s\n",y);
When I run the code;
Error opening file.
TEST /Users/lessons/AbstractLesson.java
Here is the full code;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
int main(void){
char *arr_lines, *line;
char buf_line[LINESIZE];
int num_lines = 0;
char buf[10240];
// open file
FILE *fp = fopen("/tmp/file", "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_line, LINESIZE, fp))
if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n'))
num_lines++;
// allocate memory
arr_lines = (char*)malloc(num_lines * 1024 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
line=arr_lines;
while (fgets(line, LINESIZE, fp))
if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n'))
line += LINESIZE;
// print first four lines
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST [%s]\n",y);
//x = &arr_lines[1024*0];
// y = *x;
// finish
fclose(fp);
return 0;
}
Change printf("TEST %s\n", y) to printf("TEST \"%s\"\n", y) so we can see if you have any extra whitespace characters in the filename.
fgets() returns the new line, if it's there. I didn't see where your code clears the newline. Does your path string include the new line?
Beyond that, fopen() is almost certainly working correctly. The only options are 1) The path is not correct, 2) the path has whitespace or other invalid characters, or 3) the file is not available for reading.
If you don't have a new line in your path, then you simply haven't provided enough information to resolve this issue.
I suspect the path, /Users/lessons/AbstractLesson.java, is wrong. It looks like an OSX path and it might be missing the username between Users and lessons.

Segfault - fclose / fopen

I'm having trouble with my following C code :
int main(void){
FILE* infile = fopen("file","r);
FILE* fp = NULL;
unsigned char* buffer = malloc(512);
while( fread(buffer,512,1,infile) > 0 ){ //reading a file block by block
if(buffer[0] == 0xff){
... //defining variable "name"
if(fp != NULL)fclose(fp);
fp = fopen(name,"w+");
fwrite(buffer,512,1,fp);
} else if(fp != NULL) {
fwrite(buffer,512,1,fp);
}
}
}
It seems that i can't fopen after fclose using the same pointer, why ? I need my pointer to remain accessible everywhere in the main so i can't declare a new one in my while.
EDIT: Oh god, problem solved. I was probably super tired. I was compiling the wrong file. Anyway...
Thanks, folks !
It's hard to tell why since you aren't showing us all of your code. However, reopening the file should be pretty straightforward:
#include <stdio.h>
int main(void)
{
FILE* fp = NULL;
char name[] = "somefile";
for (;;)
{
// do something
if ((fp = fopen(name, "w+")) == NULL)
break;
// do something with the file
fclose(fp);
// do something
}
return 0;
}

Resources