Search This Blog

Saturday, March 10, 2012

removing the null terminator at the end of string

removing the null terminator at the end of string

Hi There,

Don't worry I found the way to do it. See below:

while (!feof(fp)) {
fgets(line,LINE_BUF,fp);
count++;
i=strlen(line);
strncat(string1,line,i-1);
printf( " %s %d %d\n ", string1, strlen(string1) ,count );
strcpy(string1,BLANK);

The reason why I needed to remove the null terminator is I need to load this data into a linklist. I don't much about C so a little help would be handy. Thanks. 
 
 
 
====================================================
 
 strncat(char str1, char str2, strlen(str2)-1)  will give string str1 with no terminator at the end of string

write (C System Call)

write (C System Call)
write is a system call that is used to write data out of a buffer.

Required Include Files

#include <unistd.h>

Function Definition

size_t write(int fildes, const void *buf, size_t nbytes);
Field Description
int fildes The file descriptor of where to write the output. You can either use a file descriptor obtained from the open system call, or you can use 0, 1, or 2, to refer to standard input, standard output, or standard error, respectively.
const void *buf A null terminated character string of the content to write.
size_t nbytes The number of bytes to write. If smaller than the provided buffer, the output is truncated.
return value Returns the number of bytes that were written. If value is negative, then the system call returned an error.

Code Snippet

Example using standard file descriptors:
#include <unistd.h>
 
int main(void)
{
    if (write(1, "This will be output to standard out\n", 36) != 36) {
        write(2, "There was an error writing to standard out\n", 44);
        return -1;
    }
 
    return 0;
}
Example using a file descriptor:
#include <unistd.h>
#include <fcntl.h>
 
int main(void)
{
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);
 
    if (filedesc < 0) {
        return -1;
    }
 
    if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
        write(2, "There was an error writing to testfile.txt\n", 43);
        return -1;
    }
 
    return 0;
}

C Programming some function call


C Programming


File handling using open(), read(), write() and close()
The previous examples of file handling deal with File Control Blocks (FCB). Under MSDOS v3.x (or greater) and UNIX systems, file handling is often done using handles, rather than file control blocks.
Writing programs using handles ensures portability of source code between different operating systems. Using handles allows the programmer to treat the file as a stream of characters.

open()


	#include 
	int  open(  char  *filename,  int  access,  int  permission  );
The available access modes are

	O_RDONLY		O_WRONLY		O_RDWR
	O_APPEND		O_BINARY		O_TEXT
The permissions are

	S_IWRITE	S_IREAD	S_IWRITE | S_IREAD
The open() function returns an integer value, which is used to refer to the file. If un- successful, it returns -1, and sets the global variable errno to indicate the error type.

read()


	#include  
	int  read(  int  handle,  void  *buffer,  int  nbyte );
The read() function attempts to read nbytes from the file associated with handle, and places the characters read into buffer. If the file is opened using O_TEXT, it removes carriage returns and detects the end of the file.
The function returns the number of bytes read. On end-of-file, 0 is returned, on error it returns -1, setting errno to indicate the type of error that occurred.

write()


	#include  
	int  write(  int  handle,  void  *buffer,  int  nbyte  );
The write() function attempts to write nbytes from buffer to the file associated with handle. On text files, it expands each LF to a CR/LF.
The function returns the number of bytes written to the file. A return value of -1 indicates an error, with errno set appropriately.

close()


	#include  
	int  close(  int  handle  );
The close() function closes the file associated with handle. The function returns 0 if successful, -1 to indicate an error, with errno set appropriately.

©Copyright B Brown. 1984-1999. All rights reserved.

in C, Assigning output of system() to a variable

in C, Assigning output of system() to a variable


[Log in to get rid of this advertisement]
I'm new to C and Linux and I am confused on how things work. I tried to search but I don't really know if I'm searching for the right thing because lots of other things come up.

Currently, I figured out that I can use shell commands inside C by using the method system(). They display out on the screen fine, but my problem is that I need to assign them to a variable, and not have them display on the screen (yet).

I'm planning to put the output of "ls -l" to a variable. I'm thinking of an array of strings (I think there are no strings, but an array char, so I guess this is an array of array of chars?) which will contain every line of the "ls -l" command except for the first line. (I think I need it in an array because I'm supposed to scroll through it in a menu-like style where I'm following example 18 on this link:
http://www.tldp.org/HOWTO/NCURSES-Pr...tml#MENUBASICS
but I think it's another question for another time, hopefully I can figure it out and not have to though, hahah)

What I have is this, but it doesn't work.

Code:
#include 
int main() {
   char output[] = system( "ls -l" );
   printf( "%s", output);
   return 0;
}
which gives this error.
Code:
system.c: In function 'main':
system.c:5: error: invalid initializer
I believe it is wrong, but I'm completely clueless. Perhaps you can help, thanks.

Last edited by Miaire; 01-28-2005 at 08:29 AM.
 
Old 01-28-2005, 08:27 AM   #2
Hivemind
Member

Registered: Sep 2004
Posts: 273

Rep: Reputation: 30
Two things. If a function returns a pointer-to-char (dynamically allocated or static) and you want to assign the return value to a variable you do:
Code:
char *ptr = some_func_returning_pointer_to_char();
Second, system() doesn't return char* it returns int. Do a:
Code:
$ man 3 system
for more details on the return value.

The system() call is part of standard C (and C++ of course) but how it operates and what you can do with the processes it spawns is platform-dependent.
 
Old 01-28-2005, 09:29 AM   #3
deiussum
Member

Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 31
man popen

I think this does what you are looking for.
 
Old 01-28-2005, 02:39 PM   #4
jim mcnamara
Member

Registered: May 2002
Posts: 964

Rep: Reputation: 32
popen example:
Code:
#include                
#include 
#include 
#include 

void process(const char *filespec)
{
	char cmd[296]={0x0}; /* 40 + 256 */  
	char tmp[256]={0x0};
	long total=0;
	int retval=0;
	FILE *in=NULL;
	
    snprintf(cmd,sizeof(cmd)-40,"ll %s | /usr/bin/cut -c 35-45 2>/dev/null",filespec);
    in=popen(cmd, "r");
    if(in==NULL)
    {
         perror("Shell execution error");
         exit(EXIT_FAILURE);
    }           
    while(fgets(tmp,4095,in)!=NULL) 
    {
         total+=atol(tmp);
    }        
    if(!feof(in))
    {
        perror("Input stream error");
        exit(EXIT_FAILURE);
    }    
    retval=pclose(in);
    if(retval==EOF || retval==127)    
    {
        perror("Shell invocation error");
        exit(EXIT_FAILURE); 
    }    
    fprintf(stdout,"%-64s total: %d\n",filespec,total);
}

int main(int argc, char *argv[])
{
    if(argc<2)
    {
    	char filespec[256]={0x0};
    	while(fgets(filespec,sizeof(filespec),stdin)!=NULL)
    	{
    	    char *p=memchr(filespec,'\n', sizeof(filespec));
    		if(p!=NULL) *p=0x0;
    	    process(filespec);
    	}      	  
    }	
    else
    {      	
        int i=1;
        while(i
 
Old 01-30-2005, 01:40 PM   #5
Miaire
LQ Newbie

Registered: Jan 2005
Location: Atlanta, GA
Distribution: Fedora Core 3
Posts: 11

Original Poster
Rep: Reputation: 0
Thanks for the answers, I have gotten what I needed. Figured out char arrays (strings) and casting char to int in the process.

This is what I came up with:
Code:
#include 
#include 

int main()
{
   int size=0;
   FILE *in=NULL;
   char temp[256];
   
   in=popen("ls -a -l | wc -l", "r");
   fgets(temp, 255, in);
   size = atoi(temp) - 1;

   char list[size][256];

   in=popen("ls -a -l", "r"); //for reading
   fgets(list[0], 255, in); // discard total: xxx, first line
  
   int i;
   for( i = 0; i < size; i++) {
      fgets(list[i], 255, in);   
   }

   for(i=0; i < size; i++) {
      printf("%s", list[i]);
   }
   return 0;
}
It does what I expect it to do (though it probably have hidden problems somewhere like memory things I don't really understand yet. Any comments on it?) , now to format and continue on with ncurses. Thanks for help!

system() function call LINUX

system

function
int system ( const char * command );
Execute system command
Invokes the command processor to execute a command. Once the command execution has terminated, the processor gives the control back to the program, returning an int value, whose interpretation is system-dependent.

The function can also be used with NULL as argument to check whether a command processor exists.

Parameters

command
C string containing the system command to be executed.

Return Value

The value returned when the argument passed is not NULL, depends on the running environment specifications. In many systems, 0 is used to indicate that the command was successfully executed and other values to indicate some sort of error.
When the argument passed is NULL, the function returns a nonzero value if the command processor is available, and zero otherwise.

Portability

The behavior and return value are platform-dependent.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* system example : DIR */
#include 
#include 

int main ()
{
  int i;
  printf ("Checking if processor is available...");
  if (system(NULL)) puts ("Ok");
    else exit (1);
  printf ("Executing command DIR...\n");
  i=system ("dir");
  printf ("The value returned was: %d.\n",i);
  return 0;
}