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.
Related
Below is a part of my code which is having issues with file handling. The file opens fine with fopen but when I try to read or just close the file my program exits without an error. I tried to run this code independently and it works fine. Would really appreciate if someone could help me out which pointing out what I am doing wrong.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
printf("In ctrlSend\n");
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while(!feof(pFile))
{
fscanf(pFile,"%s %d",intName,&intVlan)
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE1: Updated above code
UPDATE2: Alternate code below which has same issue.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
printf("In ctrlSend\n");
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while (fscanf (pFile,"%s %d",intName,&intVlan) == 2)
{
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE3: Seems like the file is not opening, looking into it.
When you do while (!feof ...) you check each time if you have reach the end of the file. However, at no point your advance in the file (fread ?). That means this will never terminate.
Check whether the file exists or not. You should always check whether File pointer is NULL or not after opening the file. I think your program is unable to open the file and you are trying to use the file pointer without checking which is causing undefined behavior.
I am trying to read in a file and it tells me it cant find the file. I built i have a built in checker that looks to see if the file is there. I have the data file in my debug folder. Am I reading the file incorrectly? I am also using codeblocks for the IDE.
Here is my function calling my file:
char fileData[3];
int bound = 96;
//file pointer and file info
FILE *ips;
ips = fopen("data.txt", "r");
if (ips == NULL)
printf("Please check file!\n"); //this is the output I get
else {
//for loop to scan through file, and retrive the letters
int i;
for(i=0; i<bound; i++)
fscanf(ips, "%c", &fileData);
addBoggleData(head1, fileData);
}
//closes the file system
close(ips);
}
you stated the file failed to open.
Since the fopen() file name parameter has no path info.
and you stated the file is in the debug directory.
1) the execution and the file must be in the same directory
2) in this case, both the executable and the data file must be in the debug directory.
You are passing the wrong parameter to fscanf(), you should pass the address of the ith element, like this
fscanf(ips, "%c", &fileData[i]);
and to be able to tell whether the data was read succesfully, you must check the return value of fscanf(), like
if (fscanf(ips, "%c", &fileData[i]) != 1)
{
warningReadingFailure();
}
Also, the fileData array is way too small, you need to make it at least as big, as the number of bytes you intend to read from the file, i.e.
int bound = 96;
char fileData[bound];
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.
I'm having a bit of a problem with a lab I'm working on for school.
What it's supposed to do is check to see if a file exists or not. My code works fine except one line, when I try to check to see if the file exists or not. Even if the file exists, it's returning as if it's not there always. Yet if I hard code the file name into the program it works fine. I'm just trying to figure out what's causing the file name to be interpreted wrong when I pass it into accept (or fopen I've tried both).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
//open lab4.in
FILE *file = fopen("lab4.in", "r");
if (file == 0) {
printf("Unable to open lab4.in for reading");
exit(-1);
}
//get the file name to check
char filetocheck[120], output[12];
fgets(filetocheck, 120, file);
int i;
//open lab4.out for writing
unlink("lab4.out");
FILE *write = fopen("lab4.out", "w");
fgets(output, 12, file);
//check the file is there and write the characters to lab4.out
if (access(filetocheck, F_OK) == -1){
for (i=5; i<10; i++){
fputc(output[i], write);
}
} else {
for (i=0; i<5; i++){
fputc(output[i], write);
}
}
//close the files at the end
fclose(write);
fclose(file);
}
Okay, when an I/O operation like this fails, as well as the -1, you get a result in a global int errno;
Where you have your printf, replace that with
perror(argv[0]); /* or something else useful. See below */
and add the declaration
int errno;
between your #includes and the int main, and you'll get a useful error message.
(PS: Two things to check: make sure the file's where you expect it, and use ls -l to make sure it's readable.)
Update
Dammit, that's what I get for not checking the man page. The argument to perror is indeed a string, used to preface the error message.
In this statement:
fgets(filetocheck, 120, file);
you may be getting an unwanted carriage return as part of your filetocheck buffer.
At the moment my program has no problem reading in a .txt file, but my program needs to read in a text file with a different file extension (.emu is the requirement). When simply changing the same file's extension to .emu, the variable 'file' is NULL and therefore the file isn't opened, can anyone help?
Had a little look around and haven't been able to find a solution so any help is much appreciated
here's the source code:
void handleArgs (const char *filename, int trace, int before, int after) {
FILE *file = fopen(filename, "r");
char *address = malloc(MAX_ADD_LENGTH * sizeof(char));
char *instruction = malloc(MAX_INS_LENGTH * sizeof(char));
long int addressDecoded;
if (file == NULL || file == 0) {
fprintf(stderr, "Error: Could not open file");
}
else {
if (ferror(file) == 0) {
while (fscanf(file, "%s %s", address, instruction) != EOF) {
if (strlen(address) == 8 && strlen(instruction) == 8) {
addressDecoded = strtol(address, NULL, 16);
printf("%ld\n", addressDecoded);
//instruction = decodeInstruction(instruction);
}
else {
fprintf(stderr, "Error: particular line is of wrong length");
}
}
}
}
fclose(file);
}
argument 'filename' when executing is simply '/foopath/test.emu'
There's nothing special to C about the file extension. Reread your code for simple errors like changing the filename in one place, but not the other. If you're passing in the filename, pass the whole name, not just the part to the left of the period.
Files are data, and have names. What comes before the dot in a name, is just as much a part of it as what comes after -- the extensions were created just as hints as to what the file contains, but they are NOT required to be strictly related to the file's contents.
The file may not exist, or your priviledges may not be enough to open it. Or maybe there's some other kind of error. How can you diagnose this?
When you use a system call and it doesn't behave the way you want to, there's a variable called errno in errno.h (#include <errno.h>) that will contain a number representing the status of the last call. There's a huge list of symbolic constants to put names to these values, you can google it up.
For example, if you try to open a file and the returned pointer is useless, you might want to check errno to see if the file existed, or if you're exceding system restrictions for opened files, etc.