Process exited with return value 3221225477 - c

i am writing this code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int i;
fp = fopen("keimeno.txt","r");
fscanf(fp,"%d",i);
printf("%d\n",i);
fclose(fp);
return 0;
}
and the file contains:
2
Yiannis Ioannou 356
3
Today
10347
If
345
And then none
1542
John Smith 743
2
My story
3940
Feedback
682
END
When I try to run it, it exits me value 3221225477 instead of printing the number 2..
Can anyone explain why?

When you scan a number, you need to pass the address of the variable where you want to store the result:
fscanf(fp,"%d",&i);
where you have
fscanf(fp,"%d",i);
^ missing the & sign!
Your compiler really ought to have warned you - do you enable warnings when you compile?
What is happening here is that the fscanf function writes to the location given (in your case, it writes to whatever location is pointed to by the value of i, instead of writing to the location of i) . This can corrupt your memory in all kinds of nasty ways - resulting, in your case, in the program "running" for considerable time before crashing.
As #Brandin pointed out, there is a further problem with your code (although it's less likely to be the source of your problem). When you attempt to open a file, you should ALWAYS check that you succeeded. You do this with something like this:
#include <assert.h>
// at the top of the program
// attempt to open the file:
fp = fopen("keimeno.txt","r");
// and check whether you succeeded:
assert(fp != NULL); // this says "check fp is not NULL. Otherwise, quit."
Alternatively, you can make things a bit prettier with:
const char *fileName = "keimeno.txt";
const char *mode = "r";
if((fp=fopen(fileName, mode))==NULL) {
printf("cannot open file %s\n", fileName);
return -1;
}
It is almost always a good idea to put "hard wired values" near the start of your program, rather than embedding them in a function call.

Related

fopen returns non-null pointer even though file does not exist

I have a Hex file whose contents are like below:
0x14000800
0x52100000
0xD503201F
0xD503201F
0x0030A308
0x0032D138
0x00000000
0x00000000
0x00000000
0x00000000
I need to open and read this file. Below is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char ch, boot_rom_golden[16];
FILE *myFile = NULL;
myFile = fopen("/prj/vlsi/tests/boot_rom_fail/src/apps_proc0/sm6140_rom.a52100000_ROM_FULL.hex", "r");
if (myFile == NULL) {
printf("Error Reading File\n");
exit(0);
}
while ((ch = fgetc(myFile)) != EOF) {
printf("%x \n", ch);
}
I have two questions:
My understanding is if the file does not exist in the above mentioned path, then fopen should return a NULL. Observation is : even if the file does not exist in the above path (/prj/vlsi/....) , fopen is returning some value and then it goes to while loop trying to print the content. Why is this happening? My main.c and the hex file are residing in the same path. But still I tried giving the complete path which also gave the same results (i.e. even if file does not exist it is returning a non zero pointer value)
When the code executes while loop, it prints "FF" indefinitely. It should be because of reason stated above.
Please help to know the issue and how to debug these kind of issues ?
Use an int instead of a char for ch
1) Because fgetc returns an int
The C library function int fgetc(FILE *stream) gets the next character
(an unsigned char) from the specified stream and advances the position
indicator for the stream.
2) Because EOF can be defined as some number not representable by char
Same for boot_rom_golden
When I compile and run your code on my system it behaves as you would expect: myFile becomes a null pointer and the null test causes an early exit. On your machine, myFile == NULL is not true, and the early exit does not occur.
I deduce that either the code you are actually executing is not the same as the code you posted, or there is something going on in your environment that is different from mine.
Can you trace through this line by line?
Are you certain that the file named does not exist on your system at the moment this is being executed?
Perhaps there is truncation occurring? Try a short path and short filename.
Try an absolute filepath rather than a relative one.
Null is likely a macro -- perhaps it's not what you think? Try if(myFile) as an alternate.
If not resolved, post more info about your system, and tell us what myFile is when your system does not think it's equal to NULL.

File pointer still NULL after inizialization?

Hi guys i have a problem when I try to open a file. In a function when i try to read an existing text file, after i initialized the file pointer i still get the error "cannot open the file", this is the code:
FILE * fp;
fp = NULL;
fp=fopen("results.txt","r");
if(fp==NULL){
printf("error!");
exit(1);
}
using the debugger i can see the fp initialized to NULL, as requested. In the next order i can see its value changed to '0x751d9c68'.
So now it's not NULL, but the program still prints error.
PS: I used the same code to open another file in another program (that works): as always the initial value of fp is NULL, then it's changed to '0x751d9c68' (yes, it has the same value in both programs), but this time works, because fp is in fact different from NULL.
PPS: I'm using Codelite, if that helps.
EDIT: adding a printf("%p\n", fp); prints this "751D9C68"
Atleta * leggiRisultati (char fileName [], int * dim){FILE * fp; int count, i;
Atleta temp;
fp = NULL;
fp=fopen(fileName,"r");
printf("%p\n", fp);
if(fp==NULL){
perror("Error");
}
while (fscanf (fp, "%s%s%d%d%d", temp.cod, temp.nome, &temp.tN, &temp.tB, &temp.tC)== 5)
count ++;
rewind (fp);
Atleta * atl = (Atleta*) malloc(count * sizeof(Atleta));
for (i=0; i<count; i++){
int nr = fscanf(fp, "%s%s%d%d%d",atl[i].cod, atl[i].nome, &atl[i].tN, &atl[i].tB, &atl[i].tC);
//just controlling if the reading is done properly
if (nr < 4) {
printf ("cannot read the file %s",fileName);
exit (1);
}
} fclose(fp);
return atl;
}
I then use this function in this main
int main (){ int dim; Atleta * a; int i;
a = leggiRisultati("risultati.txt", &dim);
for (i =0; i<dim;i++){
stampaRisultato(a[i]);}
return 0;
}
Where "stampaRisultato" prints a line of the file just read and "Atleta" is a struct defined as:
typedef struct {
char cod[5];
char nome[21];
int tN, tB, tC;
}Atleta;
And last, yes the text file is in the same directory as my executable, yes I have the permission to open the file, the file contains a certain number of lines with 2 strings and 3 int each.
Your code should work, I can only think of 3 things that may cause this issue.
In my experience, it's oftentimes the simplist mistakes that get you, because you're so focused on the more complex elements that some things slip your mind. I can't see the rest of your program, so forgive me if any of these answers seem patronizing. Here are the first things I would check:
1.) file permissions. Make sure you're a user with permission to access and/or change the file in question. This is a pretty easy fix on linux, but I don't know about windows.
2.) file location. Make sure your text file is in the same directory as your executable. You'll need to do this if you don't specify file location.
3.) #include statements. Sometimes even the best of us get too excited to get into the bulk of our program, and we forget to include stdio.h and/or stdlib.h. If this is the case you may run into an issue where you set the file pointer to null, and then the fopen function doesn't run, so your pointer remains null.

Is this right? (Read in file in C)

For my assignment I have to create a program similar to the -wc unix command which counts words, lines, etc.
I have to read in flags and read in a text file.
I've set up all the flags and now I'm trying to read in a text file. I don't think I'm doing this right.
void readInFile(char** argv, int arg)
{
FILE *myFile;
char c;
myFile = fopen(argv[arg], "r");
if(!myfile)
{
printf("%s not found!", argv[arg]);
exit(EXIT_FAILURE);
}
}
in my main I call the function readInFile() and pass 2 arguments. Argv and the element where the file should be. So assume this to be correct.
I need help with actually opening up the file. I feel like my fopen() is wrong. I'm new to reading/writing files in C. Thanks alot!
I'm going to give you some general advice here.
Usually functions should do a single job. In this case, you are writing a function to read in a single file. So, don't pass a pointer to all the command-line arguments; pass in a single read-only pointer to the name of the file to open. Then in main() select the correct argument and pass that as the argument.
void readInFile(char const *filename)
Now, if this function will be reading in the file and doing nothing else, it needs to return the data somehow. But if this function will be doing the equivalent of wc, maybe it will read the file and print stuff, not return any data to the main() function. Then maybe the name should be improved:
void wordcount(char const *filename)
The actual call to fopen() looks fine to me.
You check for error, and then call exit() immediately. That's one way to do it. Another way to do it is to return an error code from your function, and have the caller (the main() function) check for failure, and handle the error there.
int wordcount(char const *filename)
{
// ... do stuff
if (failed)
return 1; // return nonzero error code on failure
// ... do more stuff
return 0; // success code
}
int main(int argc, char const **argv)
{
char const *filename;
int result;
filename = argv[1];
result = wordcount(filename);
if (result)
{
fprintf(stderr, "unable to open file '%s'\n", filename, result);
exit(result);
}
return 0;
}
For a program this simple, it doesn't matter much. But once you start building larger systems in software, you will be happier if your functions work well together, and part of that is making functions that return error codes rather than terminating your whole program on any error.
Why am I using 0 for the success code, and non-zero for failure? It's a common way to do it. It's easy to test for non-zero, like if (result) and there are many non-zero codes but only one zero, so you can return many different kinds of errors, but there is only one value needed for "success".
Note that instead of calling exit() from main(), you can just use the return statement. When you return 0 from main(), that signals success, and a non-zero value indicates an error. So you could just use return result; from main() if you like.
In my dummy code, I'm just returning 1 as the error code. But actually, when you call fopen() it returns an error code to you, in a global variable called errno. Probably a better option is to make your function return the actual error code as specified in errno. You could even modify the print statement in the main() function print the errno code, or use the strerror() function to turn that error code into a human-readable message.
Your call to fopen is correct, assuming that argv[arg] is a valid string which refers to a file that exists on the filesystem.
There is a small typo in the program snippet. if(!myfile) should prpbably be if(!myFile). With this change, I presume the code should work. Can you please elaborate the error faced by you?
P.S: I tried your program and it seems to work!

fopen doesn't open

I am using Code::Blocks and have set the command-line arugments via the IDE. I have also opened the executable with the proper argument and I can't manage to get a non-NULL on fopen() return. I've tried hard-coding the filename also with no success. The platform is Windows XP SP3.
The first is the one that fails, when i hardcoded it i used double backlash. Also i never knew if the second works because i never managed to start the process by opening the first one.
Obviously i put the text file in the same directory that the executable and rebuilt the executable many times, but it still doesn't work.
EDIT: I added the perror("fopen"); line in the if(finput==NULL) block. This is the output.
http://prntscr.com/h71pa
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define first_part_url "[url=http://magiccards.info/query?q="
#define second_part_url "&v=card&s=cname]"
#define end_bracket "[/url]\n"
#define output_file_prefix "output_"
char* get_card(FILE* finput);
int main(int n, char* arguments[])
{
FILE* finput;
FILE* foutput;
short int counter;
char* output_filename;
char* finalstring;
for(counter=1; counter<n; counter++)
{
finput=fopen(arguments[counter], "r");
if (finput==NULL)
{
printf("Unable to open ");
puts(arguments[counter]);
perror("fopen");
break;
}
strcpy(output_filename, output_file_prefix);
strcat(output_filename, arguments[counter]);
if((foutput=fopen(output_filename, "w"))==NULL)
{
printf("There was an error while trying to open ");
puts(arguments[counter]);
printf(" .\n");
break;
}
while(!feof(finput))
{
finalstring=get_card(finput);
fputs(finalstring, foutput);
while(((fgetc(finput))!='\n')||feof(finput));
}
printf("Autocarding ");
puts(arguments[counter]);
printf(" was a success.\n");
fclose(foutput);
}
if(finput!=NULL)
{
fclose(finput);
free(finalstring);
}
return 0;
}
char* get_card(FILE* finput)
{
char* currentcard;
char* finalstring;
currentcard=(char*)malloc(sizeof(char)*150);
fgets(currentcard, 150, finput);
/* Allocates the exact amount of space needed for the final string*/
finalstring=(char*)malloc(sizeof(char)*(strlen(first_part_url)+strlen(second_part_url)+strlen(end_bracket)+strlen(currentcard)));
/* Get all the final forum link together*/
strcat(finalstring, first_part_url);
strcat(finalstring, currentcard);
strcat(finalstring, second_part_url);
strcat(finalstring, end_bracket);
free(currentcard);
return finalstring;
}
The error you are getting, "No such file or directory" indicates that the file name you're trying to open doesn't exist.
In this case, it's probably because the program's current working directory is not the same as the directory containing the executable file.
This
finput=fopen(arguments[counter], "r");
Will only fail if you do not supply correct filenames (e.g. if there are non-ASCII characters in the names or the names do not include the correct path, fopen() opens files in the current directory if no path is specified in the file name).
This
output_filename=(char*)malloc(sizeof(arguments[counter]));
most likely does not allocate enough space for a name because arguments[counter] is a pointer, and sizeof() of a pointer is not the same as strlen(that_same_pointer) + 1.
This
output_filename=output_file_prefix;
loses the just allocated memory because you are reassigning the pointer output_filename to point to some other place, output_file_prefix ("output_").
After the above this
strcat(output_filename, arguments[counter]);
is likely going to crash your program because this is going to attempt to overwrite a string literal ("output_"), doing which causes undefined behavior per the C standard.
You have to allocate enough cumulative space for the strings that you want to concatenate and you have to concatenate them in the allocated space.
To save you even more trouble, here's another problem:
finput=fopen(arguments[counter], "r");
...
while(!feof(finput))
feof() only works after at least one read from a file. This has been asked ans answered multiple times.
Try changing
for(counter=1; counter<n; ++n)
{
to
for(counter=1; counter<n; ++counter)
It appears the code loops infinitely, therefore it would exhaust the possible elements in your argument array causing a NULL pointer to be returned.

When compiling a line counting program in Solaris an extra three lines are being as opposed to MacOSX

I wrote the following code under MacOSX in XCode. When moving the code over to a Solaris Server three extra lines are being counted and I can not figure out why.
#include <stdio.h>
#define MAXLINE 281 // 281 is a prime number!!
char words[4][MAXLINE]; // words array to hold menu items
char displayfilename[4][MAXLINE]; //filename array to hold filename for display function
char exit_choice[4][MAXLINE]; //for user interaction and end of each function
int i; //standard array variable
int loop = 1; //control variable for my loop
int main()
{
printf("Enter filename: ");
scanf("%s", displayfilename[i]);
FILE *fp;
int clo_c , clo_nc, clo_nlines;
fp = fopen(*displayfilename,"r"); // open for reading */
if ( fp == NULL )
{
printf("Cannot open for reading!\n");
}
clo_c = getc( fp ) ;
while ( clo_c != EOF )
{
if (clo_c == '\n')
clo_nlines++ ;
clo_nc++ ;
clo_c = getc ( fp );
}
fclose( fp );
if ( clo_nc != 0 )
{
printf("There are %d lines in this file.\n", clo_nlines);
}
else
printf("File is empty, exiting!\n");
}
Can anyone explain to me Solaris is adding three to clo_nlines?
You didn't initialize clo_nlines - therefore you got 'undefined behavior'.
Declaring a variable in C doesn't set its value to anything - it just allocates some memory for that variable, and whatever junk happens to be in that bit (well, not bit, but you get the idea >.>) of memory is what the variable starts out as.
There are a couple of issues here.
First one, from a bulletproof-code point of view, is #Zilchonum's point, that clo_nc and clo_nlines aren't being initialized. In old C, that means you don't have any idea what's in them to start with and so don't have any idea what you'll end with.
However, later C standards define that uninitialized variables are set to 0, so that's probably not it unless you're setting the compiler to earlier behavior with flags.
More likely is Auri's point, that different machines use different newline standards. However, I believe that Mac OS/X uses a single character for newline, just as Solaris does.
Which brings us to the file itself. Try using oc -c to see what's actually in the file. my guess is that you'll find the file on one system is \r\n newlines, but on the other system has \n newlines, probably as a result of the settings of the file transfer program you used. It has probably converted to UNIX format on one but not the other.
Did you make sure you're not counting crlf as two linefeeds?

Resources