main() { FILE *fp; fp = fopen...">

SImple C program opens a file

I am trying to create 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.

+4
source share
4 answers

Besides the old version of main , this code is not very bad. He must, by prohibiting errors, create a file.

However, since you are not checking the return value from fopen , you may get some error and not know about it.

I would 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 insist that the file is not created, but the above code says that it is, then you may fall prey to the scary "IDE works in a different directory from what you think" syndrome :-)

Some IDEs (for example, Visual Studio) will actually run your code while they are in the directory, for example <solution-name>\bin or <solution-name>\debug . You can find out by setting:

 system ("cd"); // for Windows system ("pwd") // for UNIXy systems 

in your code to see where it works. This is where the file will be created if you specify the relative path line "write.txt" . Otherwise, you can specify an absolute path to make sure that it is trying to create it at a specific point in the file system.

+8
source

What did you expect "return" from it - it opens the file on most platforms, creating it if it does not exist.

You should probably have a fclose (fp) file at the end.

+2
source

I think you want to print the contents of the write.txt file. (Assume that 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; } 
+1
source

I think you should learn some basic principles in C before you start trying to work with files. A return means that 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 nothing with the FILE pointer, except for the reason for creating a new file ...

0
source

Source: https://habr.com/ru/post/1339931/


All Articles