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.
Related
It's my first exercise about Files and I have to write some code so that if I write a word in the console, it gets printed in the file. The program ends if I input the word "fine" (it's Italian for end). It seems like the file is opened and closed correctly, the program reads the inserted chars, but nonetheless, the file remains blank.
I tried opening the file in various modes, I tried printing how many chars were read, I even tried deleting the file (but it actually does't exit even if I added exit(1).
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
FILE * fp;
char s[64];
if ((fp = fopen("prova.txt", "r+")) == NULL) {
printf("Error.\n");
exit(1);
}
do {
scanf("%s", s);
if (strcmp("fine", s) != 0) {
fprintf(fp, "%s ", s);
}
} while (strcmp("fine", s) != 0);
fclose (fp);
return 0;
}
It should save all the words in a text file, but it remains blank.
Your program looks OK. Most likely, you are checking the wrong file.
An educated guess: you are using some IDE. If this is the case, the file is created, but is created somewhere else. To be sure, print the working directory (man getcwd) somewhere in the beginning of your program, and look for the file there.
you have to use "w" to open a new file with write priviledges
change
if ((fp = fopen("prova.txt", "r+")) == NULL) {
with
if ((fp = fopen("prova.txt", "w+")) == NULL) {
EDIT: Maybe i didn't explained myself, r+ will fail if the file doesn't exist, changing it works for me
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 first post :), am starting out with C language as basic learning step into programming arena. I am using following code which reads string from text file, makes directory with that string name and opens a file for writing in that created directory. But am not able to create a file inside directory made, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <string.h>
int main()
{
char file_name[25], cwd[100];
FILE *fp, *op;
fp = fopen("myfile.txt", "r");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fgets(file_name, 25, fp);
_mkdir(file_name);
if (_getcwd(cwd,sizeof(cwd)) != 0)
{
fprintf(stdout, "Your dir name: %s\\%s\n", cwd,file_name);
op = fopen("cwd\\file_name\\mynewfile.txt","w");
fclose(op);
}
fclose(fp);
return 0;
}
What you need is to store the file name (with the path) in a c-string before opening. What you are opening is cwd\file_name\mynewfile.txt. I doubt that your directory is named cwd.
A sample could could be:
char file_path[150];
sprintf(file_path, "%s\\%s\\mynewfile.txt", cwd, file_name);
op = fopen(file_path,"w");
use
#include <sys/stat.h>
#include <sys/types.h>
instead of
#include <direct.h>
and modify
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
I see you are using the return values. That is a good start for a beginner. You can refine your error messages by including "errno.h". Instead of printing your own error messages call
printf("%s", strerror(errno));
You get more precise error messages that way.
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
You’re actually passing the string literals “cwd” and “file_name” as part of the path of the file, when I think you actually mean to put the contents of the variables with those names in there. You will probably have to piece together a string for the path. Try looking into strcat()
http://www.cplusplus.com/reference/cstring/strcat/
The program always ends up exiting. I seem to be running in to this problem frequently and I think I somehow previously fixed it but I'm not sure how. Why does it not create a file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (void){
FILE *fp;
int c;
char file_w[100];
char string[100];
printf("Enter filename\n");
fgets(file_w, 100, stdin);
fp = fopen(file_w, "w");
if (fp == NULL){
printf("Can't open file\n");
exit(0);
}
printf("Enter a string");
fgets(string, 100, stdin);
for(c = 0; c <= sizeof(string); c++)
{
fprintf(fp, "%s\n", string);
}
printf("file written");
fclose(fp);
return 0;
}
Try to print the name of the file you have entered:
printf("%s\n", file_w);
just after the line you get file_w, just to be sure to enter what you want. I same cases the terminal could be wrongly configured.
Try to enter an absolute name path, if your computer is a Linux or Unix:
/tmp/newfile.txt
If your computer is Windows... Well try to see if C:\temp\ exist (or create it) and then enter:
C:\temp\newfile.txt
In any case, remember that you can specify an absolute path, and not only the file name. So double check if you have the rights (i.e. the permissions) to write into the directory where the file should be written.
In case you want check the error and have a better description of the problem try to use the following lines instead of your code, just under the fopen
if( fp == NULL ) {
// Error, as expected.
perror( "Error opening file" );
printf( "Error code opening file: %d\n", errno );
printf( "Error opening file: %s\n", strerror( errno ) );
exit(-1);
}
strerror it is a wonderful function just because return you a description of the problem instead of an error code.
I bet the problem is "invisible character after actual name from fgets()". I'll let you figure out exactly what that character is, where it comes from and how to fix it, as "struggling to solve a problem" is part of the learning process when it comes to programming. If it was easy, everyone could do it.
If the return value of fopen is NULL it means some error occurred. I suggest you look into the errno global to see what error has occurred to help you debug why it's not opening the file.
The w flag does the following:
write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
So it should create a file when none exists, or when it does exist, overwrite its content.
If it does not do that, you have another problem, but from the little information you've given, it's hard to tell what it is.
I tried as a name of file the following:
C:\\temp\\test_file.txt
or
fopen("C:\\temp\\employees.txt", "w");
and it works fine, without errors (I made it in Windows 10. GCC win32, Version: 6.3.0).
I think that you have to use an absolute path to create the file.
use gets() instead of fgets()...it will work
.
.
gets(file_w);
.
.
I'm trying to make a program to open a file, called "write.txt".
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("write.txt", "w");
return 0;
}
Should this work? Because it returns nothing.
Other than an old variant of main, there's not really much wrong with that code. It should, barring errors, create the file.
However, since you're not checking the return value from fopen, you may get an error of some sort and not know about it.
I'd start with:
#include <stdio.h>
#include <errno.h>
int main (void) {
FILE *fp;
fp = fopen ("write.txt","w");
if (fp == NULL) {
printf ("File not created okay, errno = %d\n", errno);
return 1;
}
//fprintf (fp, "Hello, there.\n"); // if you want something in the file.
fclose (fp);
printf ("File created okay\n");
return 0;
}
If you're adamant that the file isn't being created but the above code says it is, then you may be a victim of the dreaded "IDE is working in a different directory from what you think" syndrome :-)
Some IDEs (such as Visual Studio) will actually run your code while they're in a directory like <solution-name>\bin or <solution-name>\debug. You can find out by putting:
system ("cd"); // for Windows
system ("pwd") // for UNIXy systems
in to your code to see where it's running. That's where a file will be created if you specify a relative path line "write.txt". Otherwise, you can specify an absolute path to ensure it tries to create it at a specific point in the file system.
What did you expect it to 'return' - it opens a file, on most platforms creating one if it doesn't exist.
You should probably fclose(fp) the file at the end.
I think you want to print the contents of file write.txt. (Assume it contains characters).
#include <stdio.h>
int main()
{
FILE *fp,char ch;
fp=fopen("write.txt","r");
if(fp==NULL)
{
printf("Some problem in opening the file");
exit(0);
}
else
{
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
}
fclose(fp);
return 0;
}
I think you should study some more fundamentals in C before you start attempting to work with files. A return means some data is passed back to the calling code from the called function.In this case you return 0 at the end of your program. You did not do anything with your FILE pointer except cause a new file to be created...