I am unable to open a file in c - c

i created a text file in d: drive named abc. I am unable to open it. Please tell me how to do so.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp = fopen("D:/abc.txt","r");
if(fp == NULL)
{
printf("\nCannot open");
getch();
exit(1);
}
fclose(fp);
getch();
}

You have a typo, try
fp = fopen("D:\\abc.txt","r");
instead.
Or if the file is in the same folder as the program:
fp = fopen("abc.txt","r");

correct the path, it should be "D:\\abc.txt"

You file-path looks a little bit strange. Change it to
fp = fopen("D:\\abc.txt","r");
This might work.
Apart from that, include <errno.h> and check for it, if it has failed.

fp = fopen("D:/abc.txt","r");
should be
fp = fopen("D:\\abc.txt","r");
in use \ in path instead of / in Windows and extra \ for escape sequence.
EDIT:
As you commented to others answers that fp = fopen("D:\\abc.txt","r"); also not working then check what is name actually. You might given probably wrong name by mistake, check whether you have error like this.
(1) open command prompt
(2) use DIR command to print name of file:
c:\Users\name> D:
D:\> DIR
Volume in drive D is FUN BOX
Volume Serial Number is B48A-3CE7
Directory of d:\
27-02-2013 19:23 0 abc.txt.txt
26-02-2013 22:05 <DIR> BOLLYWOOD MOVIES
27-02-2013 19:31 0 x
2 File(s) 0 bytes
1 Dir(s) 11,138,654,208 bytes free
file name is abc.txt.txt but when you see this in folder extension doesn't appears and file name looks abc.txt
I am Linux user and I normally do this mistake in Windows. That's why. May be it help you!

If you are working with TurboC put that file in the BIN directory of TC.
And specify the path as fp = fopen("abc.txt","r"); instead of any other alternate path.

The Next time , try to make the error more specific by using perror() function.
Perror() will interpret the error code , this will help you to waste less time , trying to find the type of error.
add this in your code...
if(fp == NULL)
{
perror(fp);
}
On running i got the perror message
No such file or directory.
(since i ran the program , and tried to read a file , without creating it first)
See , if this was the same problem , in your case

Related

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 (\)?

Writing the correct path in fprintf function

Apparently, there's no data regarding my question (I tried searching it out here but none of the threads I've read answered my doubt). Here it is: I'm trying desperately to figure out how can I put a correct path into the fprintf function and none of my tries have been successful. Here's the program:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp = NULL;
//opening the file
fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");
//if there's an error when opening the file, the program shuts down
if(fp == NULL){
printf("error");
exit(EXIT_FAILURE);
}
//print something on the file the program just opened (or created if not already existent)
fprintf(fp, "to C or not to C, that is the question");
//closing the file
fclose(fp);
//end of main function
return 0;
}
My question is: why my program always shuts down? What am I doing wrong? It's just a Windows problem (I saw that, on the User1 folder icon, there's a lock, could be a permission denied thing?) or I'm just putting the path in an incorrect way? I tried to use a string to save the path, I tried to change the opening mode, I even tried to disable all the antiviruses, antimalwares and firewalls I have installed on my computer but nothing, the program still doesn't create the file where I want it.
P.S. Sorry for bad English.
P.P.S. Sorry if a similar question has been already posted, I didn't manage to find it.
fp = fopen("C:\Users\User1\Desktop\myfile.txt", "w+");
The character \ is the escape character in C. You must escape it:
fp = fopen("C:\\Users\\User1\\Desktop\\myfile.txt", "w+");
Even better, windows now supports the / directory separator. So you can write:
fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");
With no need to escape the path.
Reference:
MSDN fopen, specifically the Remaks section
Use perror() to have the Operating System help you determine the cause of failure.
#define FILENAME "C:/Users/User1/Desktop/myfile.txt"
fp = fopen(FILENAME, "w+");
// report and shut down on error
if (fp == NULL) {
perror(FILENAME);
exit(EXIT_FAILURE);
}

How to discover which files exist in a folder

I have written a program, where it takes an input file, does some operations on it and gives its corresponding output file. i.e., for inp1.txt output is out1.txt, for inp2.txt output is out2.txt and so on, both in different folders.
Right now I have used a file_count variable and have used switch case method, to open the particular file.
The problem is, if I add one more file to the folder, then I have to re-edit the program with another case statement.
Please suggest me the usage of directory pointer in , I browsed all over the net but didnt get an exact solution.
Thanks a lot in anticipation.
There's no way to read the contents of a directory using only standard C APIs, so you'll have to use platform-specific APIs instead:
On *nix systems, you use opendir(3)/readdir(3)/closedir(3) to read the contents of a directory.
On Windows systems, you use FindFirstFile/FindNextFile/FindClose
If you know the file names in advance ie. they follow a pattern like this: f1.txt f2.txt fn.txt then you can loop over the files:
for (int i = 0 -> num_files)
char * filename;
filename = create_your_filename(i)
open(filename)
dostuff
close(filename)
you can follow the same pattern or even edit the filename for the output files.
Otherwise you can also call the program with all the input files in the command:
your_program *.txt
Then all of the file names will appear in argv[], which you can iterate over.
you have to find the files in input folder in runtime before processing. you can sort the files by extension,file name,created date etc...
Here is a simple function that show you if a file (in parameters) is in the path you put in argument.
Return 0 if file exit, 1 if not.
int is_file_enabled(char *path, char *filename)
{
char exec[255], line[255];
sprintf(exec, "ls %s | grep \"%s\"", path, filename);
FILE* cmd_res = popen(exec, "r");
if (cmd_res != NULL)
while (fgets(line, sizeof(line), cmd_res) != NULL)
if (line != NULL) { pclose(cmd_res); return 0; }
pclose(cmd_res);
return 1;
}

How to create a file on Ubuntu with C File I/O

I have a simple question if anyone can answer it. I'm currently starting off with Ubuntu and am learning the environment though I'm use to using Windows. On Windows if I wanted to create and write to a file I would do:
FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");
fclose(fp);
When using Ubuntu what should I put in the parameters of fopen(), say I want to have the file created on my desktop. My computer's name is "root1". Sorry if this seems like a stupid question.
FILE *fp = NULL;
fp = fopen("c:\\test.txt", "w");
if( fp != NULL ){
fprintf(fp, "Testing...\n");
fclose(fp);
} else{
perror("Could not open the file");
}
Error checking should always be done and pointers should not be left uninitialized.
in simple way of u want to take path of any file in Ubuntu then just right click and select properties ...
then it shows path copy it up and append '/filename.extension' thats it

Help with opening a file in C on Xcode

I'm trying to open a simple .rtf file called test in C. I'm using Xcode. My code is:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char * argv[]) {
FILE *filePtr;
filePtr = fopen("test.rtf", "r");
if (filePtr == NULL) {
fprintf(stderr, "Can't open \"test\"\n");
exit(EXIT_FAILURE);
}
else {
printf("File open successful\n");
int x;
/* read one character at a time until EOF is reached */
while ((x = fgetc(filePtr)) != EOF) {
printf("%c", x);
}
}
fclose(filePtr);
return 0;
}
I have the test.rtf file in the same directory as my Xcode.proj directory. My output is "File open successful", however I do not get anything read from the file. Am I doing this right? Thanks.
There's nothing wrong with that code at all. I tested it (albeit not in Xcode) with a file and the transcript was:
pax> echo hello >test.rtf
pax> ./qq.exe
File open successful
hello
So the obvious think to ask is what happens when you examine test.rtf? Does it actually have any content? Because, when I do:
pax> rm test.rtf ; touch test.rtf
pax> ./qq.exe
File open successful
I get the same behaviour you observe.
Also try renaming it to test2.rtf temporarily and make sure you get the error. It's possible it may be opening a different copy of the file than what you think (this often happens in Visual C since the directory the program runs in is not always what developers think at first).
It looks right.
As for the lack of output, two possibilities:
Are you sure the file has some content? Maybe ls -l test.rtf or dir test.rft
Possibly it has some control characters which cause the terminal to which it is written to suppress output.
Try moving test.rtf to your build directory. If your project is named MyProject, move it to MyProject/build/Debug/.
I can think of two things that could cause this problem. Either there is an error when calling fgetc, or you are getting output that you don't recognize.
fgetc() will return EOF when the end of the file is reached, or an error occurs. To determine if it's an error, just after your while loop try:
if (ferror(filePtr) != 0) printf("error: %d.\n", errno);
A .rtf file is not a plain text file. It likely contains a bunch of formatting information. You are expecting to see "Hello . . . ". but what you may actually see is something like:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf250
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040
\f0\fs24 \cf0 Hello . . .
And you are just assuming that is GDB output, not your program's output.
Based upon your recent comments, I think you have an empty file test.rtf in the directory your program is run in, and your real test.rtf file is in some other directory. Maybe your fopen() call at some point was fopen("test.rtf", "w"); instead of fopen("test.rtf", "r");, and you later modified it.
To see the directory your program is running in, add the following to your program after the FILE *filePtr; line:
char pwd[512];
if (getcwd(pwd, sizeof pwd) != -1)
printf("In directory %s\n", pwd);
else
fprintf(stderr, "Need bigger buffer, change '512' above\n");
Then, you can open a terminal, do cd <directory>, and test for yourself if the file you want is the file your program is opening.
You probably want this file to be plain text, not rich text. Rich text has a lot of formatting encoded into the file.

Resources