Understanding of file handling in C

ⅰ亾dé卋堺 提交于 2019-12-25 02:13:16

问题


How exactly do I take an input from a file in C?

As in, for instance: Say i assigned a file pointer to a particular file and want to peform certain operations. What exactly is the syntax for assigning the file pointer Assume the file, is located at C:\Acads\bin\File.txt. In my code when I try this

FILE *fp1;
fp1=("C:\Acads\bin\File.txt","r+");

It ends up giving me an error.

UPDATE: Okay so here is my main doubt.

How exactly do i tell the compiler that my file is located at so and so path. I've tried doing everything you guys have told me but to no avail.


回答1:


I think you ran into a typo: It should say:

fp1=fopen(filename,"r+");

Also you have to escape each backslash char \ with another backslash:

fp1=fopen("C:\\Acads\\bin\\File.txt","r+");

This is because the \ begins an escape sequence. E.g: \n would mean a newline. \\ is expanded to a simple backslash.




回答2:


This should give you an overview of file handling in C. You can use fopen to open a file & use perror to see if something went wrong. Something on these lines:

FILE *fp;
fp= fopen("C:\\Acads\\bin\\File.txt","r+"); /* You have to escape \ in C as it is a special character*/
if ( fp == NULL)
{
  perror("fopen");
  /*Handle error*/
}
/* File operations */
fclose(fp);

Hope this helps!




回答3:


Here's a simple example of using fopen

FILE *fp;
fp = fopen(path, "r+");

Take a look at man fopen.




回答4:


You should open the file before you try to read. Here is a complete example of how to open a file and read consequent lines.

http://www.phanderson.com/files/file_read.html




回答5:


A file pointer is a pointer to a struct containing certain information about the file, like where it's located, how big it is and other things depending on your operating system and libc implementation.

Now, the point is that you don't need to worry about what that struct really contains. You just know that you can have a pointer to one and that the library functions know what to do with it. This gives the wonderful feature of portability, meaning that your code can work unaltered even on systems which have a completely different way of handling files.



来源:https://stackoverflow.com/questions/8604521/understanding-of-file-handling-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!