Thread: how to use system function?

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    168

    how to use system function?

    Code:
    #include "stdio.h"
    #include "stdlib.h"
    int main()
    {
        system("rm -f file1.txt");
        return 0;
    }
    If there is file1.txt in current directory, rm -f file1.txt
    if there isn't file1.txt, error occurs:"Could not Find file1.txt"

    How to solve this bug?
    How to add code to correct this bug?

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    There is no standard function for that. You need to use a platform-specific function. What OS are you running?

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    BTW, for standard headers, use <> not "".

    Code:
    #include <stdio.h>
    #include <stdlib.h>

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The system function should be used sparingly, if at all. It's unsafe for users, as it exposes yet another entry point for compromises, and it's unsuitable for the programmer because of the lack of control. Figure out what you want to do, and then locate the API functions necessary to accomplish the task. In this case, it looks like you just need the 'remove' function (not sure what the -f switch does, though).

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by cyberfish View Post
    There is no standard function for that. You need to use a platform-specific function. What OS are you running?
    Linux ( Red Hat) is my OS!

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by Sebastiani View Post
    The system function should be used sparingly, if at all. It's unsafe for users, as it exposes yet another entry point for compromises, and it's unsuitable for the programmer because of the lack of control. Figure out what you want to do, and then locate the API functions necessary to accomplish the task. In this case, it looks like you just need the 'remove' function (not sure what the -f switch does, though).
    I want to append writing into file
    Code:
    //APPEND WRITE INTO FILE: write one file into end of the other file
    void appendWriteIntoFile(char *f1,char *f2)
    {
         FILE *fa;
         if( fa = fopen(f1,"a") ) { } else { printf("Error:Can't open %s.\n",f1); exit(1); }
         FILE *fo;
         if( fo = fopen(f2,"r") ) { } else { printf("Error:Can't open %s.\n",f2); exit(1); }
         
         while ( !feof(fo) )
         {
               char buf[700] = {'\0'};
               fgets(buf,700,fo);
               if ( strlen(buf) > 3 )
                  fprintf(fa,"%s",buf);
         }
         fclose(fa);
         fclose(fo);
    }

  7. #7
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    not sure what the -f switch does, though
    -f = force (no prompt).

    For Linux, there is access().
    access

  8. #8
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    So do you want to append or remove?

  9. #9
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by cyberfish View Post
    So do you want to append or remove?
    I want to append.
    I have two files ,one name is file1 ,the other name is file2;
    I want to join them,then create a new file whose name is file3;

    but , first of all , I must identify whether the file3 exists .
    if exists, rm -f file3

  10. #10
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    No need to check for the file, then.

    fopen with "w" will automatically erase the file if it already exists.

  11. #11
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by cyberfish View Post
    No need to check for the file, then.

    fopen with "w" will automatically erase the file if it already exists.
    I understand your meanings,you want FILE POINTER to alway open until end,
    aim to every file, I want to open FILE POINTER when appending one file then fclose it

    I write a append function appendWriteIntoFile(char *f1,char *f2),
    its function is that appending f2 to f1.

    Code:
    for ( file1.....file10)
    {
          append(file0,file_x);
    }
    At the beginning of this program,I might identify whether is file0 exists!
    how I solve it?

  12. #12
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by cyberfish View Post
    -f = force (no prompt).

    For Linux, there is access().
    access
    access is Ok!
    remove function also is OK!
    thanks !

  13. #13
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Consider using return values instead of exiting the main program. Also, EOF should always be checked after the read, but before the write. Here's an example of a correct (I think) approach:

    Code:
    
    
    #include <stdlib.h>
    #include <stdio.h>
    
    int main( int argc, char** argv )
    {
    	enum
    	{
    		success, 
    		invalid_usage,
    		input_file_not_accessable, 
    		output_file_not_accessable, 
    		file_system_error
    	};	
    	int
    		ch,
    		result = success;
    	FILE
    		* in = 0, 
    		* out = 0;
    	if( argc != 3 )
    		result = invalid_usage;
    	else
    	{
    		if( ( in = fopen( argv[ 1 ], "rb" ) ) == 0 )
    			result = input_file_not_accessable;
    		else 
    		{
    			if( ( out = fopen( argv[ 2 ], "a+b" ) ) == 0 )
    				result = output_file_not_accessable;
    			else
    			{
    				while( ( ch = fgetc( in ) ) != EOF )
    					fputc( ch, out );
    				if( ferror( out ) || ferror( in ) )
    					result = file_system_error;
    				fclose( out );
    			}
    			fclose( in );
    		}
    	}
    //	printf( "%d\n", result );
    	return result;
    }
    EDIT: Yes, I realize now that I misspelled 'accessible', and yes, I'm also too lazy to fix it.
    Last edited by Sebastiani; 12-30-2009 at 02:47 AM.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You could use a small char array to make up your filenames:

    Code:
    #include <stdio.h>
    
    int main() {
      int i;
      char filename1[] = {"file_0.txt"};
      char filename2[] = {"file_0.txt"};
      char n = '0';
    
      for(i = 0; i < 3; i++) {
        filename1[5] = n;
        filename2[5] = ++n;
        printf("\n New filenames are %s and %s", filename1, filename2);
      
        /* call your append file function here */
      
        ++n;
      }
    
      n = getchar();
      return 0;
    }
    One way to determine if a file exists, is to open it in read mode. If fopen() finds a file with that name, it will return the address of it's file pointer to you.

    If the file doesn't exist, fopen() will return NULL.
    Last edited by Adak; 12-30-2009 at 02:52 AM.

  15. #15
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by Adak View Post
    If fopen() finds a file with that name, it will return the address of it's file pointer to you.

    If the file doesn't exist, fopen() will return NULL.
    Usually, but not always. fopen will return NULL for several errors, a few of which can be found at the manual of open():
    EACCES The requested access to the file is not allowed, or search per‐
    mission is denied for one of the directories in the path prefix
    of pathname, or the file did not exist yet and write access to
    the parent directory is not allowed. (See also path_resolu‐
    tion(7).)

    EEXIST pathname already exists and O_CREAT and O_EXCL were used.

    EFAULT pathname points outside your accessible address space.

    EFBIG See EOVERFLOW.

    EINTR While blocked waiting to complete an open of a slow device
    (e.g., a FIFO; see fifo(7)), the call was interrupted by a sig‐
    nal handler; see signal(7).

    EISDIR pathname refers to a directory and the access requested involved
    writing (that is, O_WRONLY or O_RDWR is set).

    ELOOP Too many symbolic links were encountered in resolving pathname,
    or O_NOFOLLOW was specified but pathname was a symbolic link.

    EMFILE The process already has the maximum number of files open.

    ENAMETOOLONG
    pathname was too long.

    ENFILE The system limit on the total number of open files has been
    reached.

    ENODEV pathname refers to a device special file and no corresponding
    device exists. (This is a Linux kernel bug; in this situation
    ENXIO must be returned.)

    ENOENT O_CREAT is not set and the named file does not exist. Or, a
    directory component in pathname does not exist or is a dangling
    symbolic link.

    ENOMEM Insufficient kernel memory was available.

    ENOSPC pathname was to be created but the device containing pathname
    has no room for the new file.

    ENOSPC pathname was to be created but the device containing pathname
    has no room for the new file.

    ENOTDIR
    A component used as a directory in pathname is not, in fact, a
    directory, or O_DIRECTORY was specified and pathname was not a
    directory.

    ENXIO O_NONBLOCK | O_WRONLY is set, the named file is a FIFO and no
    process has the file open for reading. Or, the file is a device
    special file and no corresponding device exists.

    EOVERFLOW
    pathname refers to a regular file that is too large to be
    opened. The usual scenario here is that an application compiled
    on a 32-bit platform without -D_FILE_OFFSET_BITS=64 tried to
    open a file whose size exceeds (2<<31)-1 bits; see also O_LARGE‐
    FILE above. This is the error specified by POSIX.1-2001; in
    kernels before 2.6.24, Linux gave the error EFBIG for this case.

    EPERM The O_NOATIME flag was specified, but the effective user ID of
    the caller did not match the owner of the file and the caller
    was not privileged (CAP_FOWNER).

    EROFS pathname refers to a file on a read-only file system and write
    access was requested.

    ETXTBSY
    pathname refers to an executable image which is currently being
    executed and write access was requested.

    EWOULDBLOCK
    The O_NONBLOCK flag was specified, and an incompatible lease was
    held on the file (see fcntl(2)).

    So, yes, NULL might indicate the file does not exist. But it may also mean a lot of different things. No permission, no memory are two examples. So it'd be required to check errno as well.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. measuring system resources used by a function
    By Aran in forum C Programming
    Replies: 1
    Last Post: 03-13-2006, 05:35 PM
  5. I need help with passing pointers in function calls
    By vien_mti in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 10:00 AM