At first I wanted to open a file and read its contents, in C, however, in doing so, I was unable to run the program without errors, I even tried to just open the file, and not read anything, I did exactly what I saw on other questions like this and got errors, here is the code.
#include <stdio.h>
void main(void){
FILE *file = NULL;
file = fopen('list.txt', 'r');
}
(Repeating BLUEPIXY's comment as an answer so search finds it)
Your mistake is that in 'list.txt', 'r' the ' does not mark a string in 'C' (unlike in python) you must use ".
The ' is used to specify `a single character variable.
First of all do you have a file called list.txt, and what if the program does not find list.txt. It can't read the file so you must check for exist file.
#include <stdio.h>
int main (void) {
FILE *file_exist = fopen("list.txt", "r");
if (file_exist) {
printf("File Founded");
//Insert what do you want to do with the file like fscanf? fgetc? Up to you
}
else {
printf("File Not Found");
//If there is no file, You can start ignore reading the file since will cause error dont know what to read
}
}
Here you can avoid error, while reading your file.
Related
I'm learning how to read content from a file in C. And I manage to scrape through the following code.
#include <stdio.h>
#include <stdlib.h>
void read_content(FILE *file) {
char *x = malloc(20);
// read first 20 char
int read = fread(x,sizeof(char),20,file);
if (read != 20) {
printf("Read could not happen\n");
}
else {
printf("the content read is %s",x);
}
free(x);
return;
}
int main(int argc,char *argv[]) {
FILE *fp;
fp = fopen("test.txt","w+");
read_content(fp);
fclose(fp);
return 0;
}
But for some reason (which I'm not able to understand) I see the read bytes count as 0.
The problem is that you open the file with the w+ mode. There are two possibilities:
if the file doesn't exist, it will be created empty. Reading from it immediately gives end of file resulting in fread() returning 0.
if the file does exist, it will be truncated i.e. changed into an empty file. Reading from it immediately gives end of file resulting in fread() returning 0.
If you just want to read from the file (as per your example), open it in mode r. If you want to read and write without destroying its existing content, use mode r+.
Whatever mode you choose, always check that fopen() returns non null and print the error if it returns null (this is not the cause of your problem but is best practice).
From Man Page w+ flag:
Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated.
You are probably trying to open a file which doesn't exist at the path you provided, or is read-only as #WhozCraig suggested in comment. This means a new file is being created, an empty file! hence you are seeing 0 bytes read.
To sum up, The fopen is failing, in that case you need to check the return value if it is equal to -1.
To find what was the error, you can check the errno as it is set to
indicate the error.
If you are only intending to read, open the file with r flag instead of w+
The problem lies within this line of code:
fp = fopen("test.txt","w+")
the "w+" mode, clear the previous content of the file and the file will be empty when you just going to read the file without writing anything to it. Hence, it is printing "Read could not happen" because you are trying to read an empty file.
I would suggest you to use "r+" mode, if you are willing to read and then write into the file. Otherwise, r mode is good enough for simple reading of a file.
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);
My code takes a string, writes it in a .dat file and then reads it from the .dat file and posts it in the console.
My problem is that the .dat from what I know should be coded, and I couldn't simply open it and see what's there. But when I open the d.at file with notepad, it behaves the same as a .txt file and I can see all it's written.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f;
char s[100],g[100];
if((f=fopen("text.dat","wb"))==NULL)
{
exit(1);
}
printf("write text: "); gets(s);
int n=strlen(s);
fwrite(s,sizeof(s[0]),n,f);
fclose (f);
if((f=fopen("text.dat","rb"))==NULL)
{
exit(1);
}
fread(g,sizeof(g[0]),strlen(s),f);
puts(g);
return 0;
}
Nothing is wrong with your .dat file.
My problem is that the .dat from what I know should be coded
What does coded mean? Changing a file extension from .txt to .dat doesn't make any difference, in fact it's just renaming it. Microsoft Windows or any other OS may open specific file types with specific programs by default, but that doesn't mean that you can't use the program of your choice.
In this case, notepad will simply read the file contents, which are the characters you read from keyboard and written to it, without any "coding" (except ASCII encoding of course).
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 (\)?
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)