开发者

What is a FILE * type in Cocoa,and how properly use it?

开发者 https://www.devze.com 2023-04-12 16:54 出处:网络
I\'m trying to run Bash commands from my Cocoa APP. And receive开发者_如何转开发 the output. I\'m executing all that commands, with Admin Privilege.

I'm trying to run Bash commands from my Cocoa APP. And receive开发者_如何转开发 the output. I'm executing all that commands, with Admin Privilege. How to get output from Admin Priveleges bash script, called from Cocoa?

I guess I need FILE * type to store output, but I don't know how to use it.

What is FILE * type? And how should I use it?


FILE * is a C type and it hasn't got anything to do with Cocoa. It is a handle for an opened file. Here is an example:

#include <stdio.h>

int main () {
  FILE *file;
  file = fopen("myfile.txt", "w"); // open file
  if (!file) { // file couldn't be opened
    return 1;
  }
  fputs("fopen example", file); // write to file
  fclose(file);
  return 0;
}

In Cocoa, you should normally use NSString's and NSData's writeToURL:atomically:encoding:error: and writeToURL:atomically: methods, respectively.


FILE is an ANSI C structure is used for file handling. fopen function return a file pointer. This pointer, points to a structure that contains information about the file, such as the location of a buffer, the current character position in the buffer, whether the file is being read or written, and whether errors or end of file have occurred. Users don't need to know the details, because the definitions obtained from stdio.h include a structure declaration called FILE. The only declaration needed for a file pointer is exemplified by

FILE *fp;
FILE *fopen(char *name, char *mode);

This says that fp is a pointer to a FILE, and fopen returns a pointer to a FILE. Notice that FILE is a type name, like int, not a structure tag; it is defined with a typedef.

#include <stdio.h>

int main()
{
   FILE * pFile;
   char buffer [100];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else
   {
     while ( ! feof (pFile) )
     {
       if ( fgets (buffer , 100 , pFile) != NULL )
         fputs (buffer , stdout);
     }
     fclose (pFile);
   }
   return 0;
}

This example reads the content of a text file called myfile.txt and sends it to the standard output stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号