fscanf not reading in file - c

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];

Related

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.

Can not open files with c

Im supposed to write a program that opens an excel file, reads the numbers on the file, multiplies them by 9.8 and the shows the answer in another excel gile.
I wrote this, and I did not get any errors in the compiler, but when I run it, it does not open any files. How do I make it open the files?
#include <stdio.h>
int main() {
FILE *archivo;
FILE *archivoSalida;
int masa;
float peso;
archivo = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoEntrada.txt", "r");
archivoSalida = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoSalida.txt", "r");
if (archivo != NULL)
{
printf("The file was opened succesully");
while (fscanf(archivo,"%d", &masa)!= EOF)
{
peso=masa*9.81;
fprintf(archivoSalida, "%f\n", peso);
}
}
else
{
printf ("Error");
}
fclose(archivo);
fclose(archivoSalida);
return 0;
}
You'll want to fopen the output file ("archivoSalida") with mode "w" (for write) instead of "r" (for read). See e.g. http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html.
You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?
Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.
Your file denominated by archivoSalida is opened in read mode ('r').
You should also check the return codes of read/writes functions to be sure everything happen as wanted.
The file names look Windows-ish. Is it possible that all of the forward slashes (/) that you have in both file names should really be back slashes (\)?

'fopen' in C can't open existing file in current directoy on Unix

I am using fopen(3) in C to read file and process it. The file is present in current working directory where the binary exists, but I am unable to read the file (Linux environment / Cygwin environment).
Here is the sample code:
C code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *inFile;
static char fileName[255];
int process_file(FILE *inFile)
{
char ch;
inFile = fopen(fileName,"r");
if (inFile == NULL)
{
perror(fileName);
exit(1);
}
else
{
// Process file
}
fclose(inFile);
return 0;
}
int main(int argc, char *argv[])
{
printf("Enter filename to process \n");
scanf("%s", fileName);
process_file(inFile);
getchar();
return 0;
}
I have file permissions set to 777 in the current directory. The resulting binary as well as my source code reside in this directory where the input file exits. Why is the file not opened?
Update :
This question was written in few years back and this code could be improved a lot.
1. The process file should accept char * or char array instead of file pointer
2. unused variables can be removed
3. unused libraries or include files can be removed
4. Can make use of argv to accept filename with path from cmdline
5. return instead of exit in process_file and also proper return code instead of returning 0 from process_file.
I should have asked this question little more elaborate...
I had three functions to process the same file, like process_fil1e1(), process_file2() and process_file3() even though I called fclose() in all three functions. Somehow the file handle was not closed that properly or the file pointer pointed to EOF or some undefined behavior. It was not working fine.
When I used a single process file and rewind() together, it worked fine...
Be sure to input file name with its extension. This may cause problems with reading the file.
If you know the extension of the file you can input only the name and after that make the program add the extension. After scanf("%s", fileName); add strcat(fileName, ".txt"); if you want to enter only the name without extension and the file you read has extension .txt.
Your inFile and fileName variables are extern so you don't need to have arguments for the function process_file();, any function can access those variables.
You can change function int process_file(); to void process_file(); and delete return 0, you don't need that.
You have declared the inFile and fileName as global. You should change your function prototype from
int process_file(FILE *inFile)
to
int process_file()
This would at least make your program more clear. Now regarding your problem: It would almost certain be that you are doing something wrong in the input file (like not putting in the file extension) in your input. Remember, you need to pass the complete file name (including the extension which on some systems like Windows (by default) would be hidden). Otherwise, the logic looks correct to me, and it should work fine.

Files in C, how to do input

This is my output function
void output(int n){
FILE *fp;
fp = fopen("sqrt.txt", "w");
for(int i = 1; i < n; ++i){
fprintf(fp, "%.2f\n", sqrt(i));
}
fclose(fp);
}
I'm required to make an input function (it reads the output function) that prompts the user to enter the name of the file to be opened. I need the contents of the file to be printed. If it is an invalid file name, the program should exit.
How to start this exercise?
To read a file in C, you use the fopen function almost just like what you had before, except passing it read rather than write. To read the file after it's been opened, you can use fread or fscanf. The file can be closed as usual with fclose.
If you want to read from the user rather than from a file, you can use fread with stdin instead of a file or (for the equivalent of fscanf) scanf.
fopen return a pointer that can be null: if it is, that mean your process was not able to open the file. So you have to check the return value of fopen to know if the file exist (I am not sure, but if the file exist and the return value is NULL, that means you probably have not the necessary right).
Hope it can help.

Reading in .txt file with different extension in C

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.

Resources