How to read from a text file I made in C - c

I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.

Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}

It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);

Related

How to read a configuration file, or create one if it's missing

How do you make a file, but only if it doesn't already exist? Like.. I want to read a text file, but if it doesn't exist, I want to create one with some default text.
I can create the file with the default text easy enough. And I can append or overwrite it if it already exists.
But if it already contains some text, I want to READ FROM it. Not WRITE TO it. Like you might do with a dot file or configuration file, to set a default configuration in the event the file is missing.
This is quite simple with Python, but I'm trying to make the transition to C, and It's more challenging than I'd anticipated.
So my function basically looks something like this so far. The text is just a placeholder for whatever the real text might be.
main() {
FILE *fp;
fp = fopen("./filename.txt", "w");
fprintf(fp, "some default text\n");
fclose(fp);
}
So just to clarify: If ./file.txt already exists, it shouldn't be written to. It should be read from.
When I say "read from", it could be printed to stdout, or stored in an array for instance, but that's probably beyond the scope of the question.
Considering your example there are two main mistakes:
You don't check the result of fopen thus you don't know whether your file has been successfully opened (here is the key to the answer).
printf function prints directrly to stdout and you have to use fprintf one for printing to your configuration file.
I propose the following: try to fopen your configuration file (e.g. ./filename.txt) for r and check the result of this call. Upon successful completion fopen return a FILE pointer to your existing configuration file. If the file doesn't exist fopen returns NULL and errno is set to ENOENT. In this case you can create a new configuration file and write a default config into it.
Please see man 3 section for the corresponding docs.
UPD:
Here is PoC for the proposal
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE *fp = fopen(".rc", "r");
if (!fp)
switch (errno) {
case ENOENT:
fprintf(stderr, "No config found, creating the default one\n");
fp = fopen(".rc", "w");
if (!fp) {
perror("Failed to create default config: ");
return EXIT_FAILURE;
}
/* write default config here */
break;
default:
perror("Failed to open existing config: ");
return EXIT_FAILURE;
}
/* read existing config here */
return EXIT_SUCCESS;
}
Use stat before opening your file. If the stat is successful then the file exists, if it is not, check for ENOENT in errno.
Example
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat file_infos;
char file_path[] = "/whatever"
if (stat(file_path, &file_infos) != 0)
{
if (errno == ENOENT)
{
// Do whatever when the file wasn't found
}
else
{
// Error accessing the file, check the errno for more infos
}
}
else
{
// File exists, do whatever you like with it.
}
}
Enjoy :)

Check if a file is empty or not

How can I check if a text file has something written or not. I tried:
LOGIC checkfile(char * filename)
{
FILE *pf;
pf=fopen(filename,"wt");
fseek(pf,0,SEEK_END);
if(ftell(pf)==0)
printf("empty");
}
This function returns empty everytime, even in my text file I have few words or numbers written.
The problem is that you opened the file for writing. When you do that, everything in the file is lost, and the length of the file is truncated to 0.
So you need to open the file for reading. And the easiest way to see if the file is empty is to try to read the first character with fgetc. If fgetc returns EOF, then the file is empty.
First of all: DO NOT OPEN THE FILE FOR WRITING!
second: for knowing about file status in C you can use fstat which is in sys headear file!
You can use struct stat for using this function
here is a simple example:
#include <sys/stat.h>
int main(void)
{
int fields = 0;
int size = 0;
// Open the file test.txt through open()
// Note that since the call to open directly gives
// integer file descriptor so we used open here.
// One can also use fopen() that returns FILE*
// object. Use fileno() in that case to convert
// FILE* object into the integer file descriptor
if(fields = open(file_path, "r")){
struct stat buf;
fstat(fields, &buf);
size = (int)buf.st_size;
}
printf("size of file is %d", size);
return 0;
}
Note: I just include a header file that related to fstat. You can add other header files yourself
What about using fscanf to read the file, and check if something was actually read?
FILE *fp;
char buff[255] = "";
fp = fopen(filename, "r");
fscanf(fp, "%s", buff);
if (!*buff)
printf("Empty\n");
else
printf("%s\n", buff);
fclose(fp);

'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.

How can I get a file pointer ( FILE* ) of known file in a specific path?

to read/write a file i need file pointer in language C in Unix environment.
I know a file name and path, but how to get file pointer using its name and path.
#include <stdio.h>
FILE * pFile;
pFile = fopen ("myfile.txt","w");
Import the standard input/output header like so
#include <stdio.h>
And then create a pointer for the file you want to open.
FILE * file_pointer;
file_pointer = fopen ("[path to file]","w");
fclose(file_pointer);
NOTE: Specify whole path to file if it is not in the same directory as your source file.
Dont forget to close the file after you have done the operations you need
According to the post from ssmithstone:
#include <stdio.h>
FILE * pFile;
/* open file and check if was successful */
if ((pFile = fopen("myfile.txt", "w")) == NULL)
{
/* couldn't open file; do some error handling if u want */
}
else
{
/* do s.th. */
/* close file */
fclose(pFile);
}
In this case w means writing. For other options check the link posted by Yu Hao.
Seems like you are new in C programming, I've written a C program for you, you can analyse it and I believe it will be definitely helpful to you.
#define size 50
#include <stdio.h>
int main()
{
char name[size];
FILE *file;
file = fopen("your_file.txt","w");
printf("Please enter your first name\n");
scanf("%s",name);
fprintf(file,"%s",name);
fclose(file);
return 0;
}
Details:
In line 7 the second parameter w is used as file open mode - with write privileges.
The file pointer is used to create / open a file with name "your_file.txt".
function fprintf() is same as printf() function but it writes not on console but to your file.
finally we need to close the file writing operations thus we use fclose() function
Update:
To specify your path you can write your file path with your filename.fileextension
for example: You can write it as
file = fopen("/home/depthgr8/Desktop/your_file.txt","w");
This will create your_file.txt in given path if your path exists otherwise it will throw a runtime exception - segmentation fault (core dumped)

Read text into C. Get a bad exec error

Trying to learn C. Want to read the first line of a text file, my code is:
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
return 0;
}
I'm doing this in xCode. I get a exc bad access error.
test.txt definitely exists. It has one line that says "this is a text file"
try this after fopen() call:
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
and add the headers:
#include <errno.h>
#include <string.h>
The code looks fine, so my guess is that the program is not run in the same working directory as the file. Try placing the file in, say, /tmp/test.txt and use absolute path in fopen.
You don't check if the FILE is NULL. It may not be opened for a several reasons.

Resources