Sponsored Content
Top Forums Programming Results Of A Variable Into An Array Using C Language Post 302929350 by jim mcnamara on Friday 19th of December 2014 04:53:06 PM
Old 12-19-2014
Corona corrected your problems. Consider a more generalized approach.
This is not production code. It could use more error checking, for example. I use it for quick and dirty stuff.

It breaks a file into an array of lines based on the \n character.
You could have it break on spaces or punctuation or whatever, in order to emulate creating an array of words in a file. Just change the delimiter in the split call. For large files create a larger result[] array.

You could call split again on a line and split the line by spaces + punctuation to get a word count, for example. You could add a regex call and split on just about anything.


Code:
#include "min.h"

#define AVG_LINE_SZ 20

// from M Rochkind
ssize_t readall(int fd, char *buf, size_t bytes)
 {
     ssize_t bytes_read = 0;
     ssize_t n=0;
     do {
         if ((n = read(fd,
                       &buf[bytes_read],
                       bytes - bytes_read)) == -1)
         {
             if (errno == EINTR)  // resume on INTR
             {
                 continue;
             }
             else
             {              
                 return -1;
             }
         }
         if (n == 0)
             return bytes_read;
         bytes_read += n;
     } while (bytes_read < bytes);
     return bytes_read;
 }

char **split(char **r, char *src, const char *delim)
{
   int i=0;
   char *p=strtok(src, delim);
   for( ; p; p=strtok(NULL, delim) )
   {
      r[i++]=p;
      r[i]=NULL;
   }
   return r;
}

size_t filesize(const char *fname)
{
         struct stat st;
         if(stat(fname, &st)== -1 )
         {
            fprintf(stderr, "cannot stat: %s %s\n", fname, strerror(errno));
            exit(1);
         }
         return st.st_size;
}

char *readfile(char *buf, char *fname, size_t len, char **result)
{
   FILE *fp=fopen(fname, "r");
   if(readall(fileno(fp), buf, len)>0)
   {
     split(result, buf, "\n");  // split on newlines     
     fclose(fp);
   }
   else
   {    
     perror("");
     exit(1);
   }
   return buf;

}

int main(int argc, char **argv)
{
   size_t len=(argc>1)? filesize(argv[1]): 0;
   char *result[8192]={NULL};  // <- this a problem for larger files
   int i=0;
   char *buf=(len>0)? malloc(len+2): NULL;
   if(buf==NULL) {perror(""); exit(1);}
   readfile(buf, argv[1], len, result);
   while(result[i])
     printf("%s\n", result[i++]);
   free(buf);
   return 0;  
}

This User Gave Thanks to jim mcnamara For This Post:
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

store awk results in a variable

I try to get the month (of last save) and the filename into a variable, is this possible ? something like this : for month in `ls -la | awk '{print $6}'` do if ] then a=filename of the matching file cp $a /Sep fi thanks, Steffen (1 Reply)
Discussion started by: forever_49ers
1 Replies

2. UNIX for Dummies Questions & Answers

Setting the Results of a Command to a Variable

Hi, Hi, I run the command: hostname to get the host back from the server: db201 Now, I need to take that result and set it to a variable. Can anyone help me with this?? I need to be able to use the same script on multiple servers so I do not want to hardcode the hostname result into... (1 Reply)
Discussion started by: stky13
1 Replies

3. Shell Programming and Scripting

Results of command execution into array

Hi Can anybody tell me how can I dump the results of execution of a command into array form? For example, I want to execute: and put each part of the result in an array element: Thanks (2 Replies)
Discussion started by: alirezan
2 Replies

4. Shell Programming and Scripting

Compare Array results

Hi, In a kshell , i need to compare the results of two array . each Non-match value should copy to a new array. For example: ========== Array one contain the following values: A B C Array two contain the following values: C F A E After comparing this arrays , a new array should... (4 Replies)
Discussion started by: yoavbe
4 Replies

5. UNIX for Dummies Questions & Answers

how to - redirect query results to a variable

How can I send the results of a query to a unix variable. I basically want to run a query then do some logic on the results. Trying to redirect the result into a variable I define in the script. select count(*) as counter from table - nut to redirect the "count" returned from the query... (2 Replies)
Discussion started by: rstone
2 Replies

6. Shell Programming and Scripting

Adding results of a find to an array

I'm trying to add the paths of all the xml files in certain directories to an array. I want to use the array later in my code. Anyway, for some reason this isn't working. Any help would be appreciated. Path_Counter=0 for result in "find * -name '*.xml'"; do XmlPath="$result" echo... (2 Replies)
Discussion started by: Fly_Moe
2 Replies

7. Shell Programming and Scripting

Adding grep'd results in a variable

Here is one I am baffled with; I have not used unix for a while and now that I am back it has been fun remembering and I have enjoyed it, for the most past. this is in ksh. I need to search in a file for the line with X1 and cut columns 20-25, put them into a variable, added them (dollar... (3 Replies)
Discussion started by: CougarMutt
3 Replies

8. Shell Programming and Scripting

Storing the SQL results in array variables

Requirement 1) I need to execute 15 SQL queries in oracle through linux script. All these query results needs to be stored in array variables. Requirement 2) And these 15 queries needs to be executed in parallel. Requirement 3) Once all the queries executed then the shell script should... (3 Replies)
Discussion started by: Niranjancse
3 Replies

9. Shell Programming and Scripting

Append awk results into file or array

for a in {1..100} do awk '{ sum+=$a} END {print sum}' a=$a file1 > file2 done I know I will get only one number if following the code above, how can I get 100 sum numbers in file2? (2 Replies)
Discussion started by: wanliushao
2 Replies

10. Shell Programming and Scripting

I want to add a variable for the results from the formula of one variable and results of another var

Good morning all, This is the file name in question OD_Orders_2019-02-19.csv I am trying to create a bash script to read into files with yesterdays date on the file name while retaining the rest of the files name. I would like for $y to equal, the name of the file with a formula output with... (2 Replies)
Discussion started by: Ibrahim A
2 Replies
ppmtosixel(1)						      General Commands Manual						     ppmtosixel(1)

NAME
ppmtosixel - convert a portable pixmap into DEC sixel format SYNOPSIS
ppmtosixel [-raw] [-margin] [ppmfile] DESCRIPTION
Reads a portable pixmap as input. Produces sixel commands (SIX) as output. The output is formatted for color printing, e.g. for a DEC LJ250 color inkjet printer. If RGB values from the PPM file do not have maxval=100, the RGB values are rescaled. A printer control header and a color assignment table begin the SIX file. Image data is written in a compressed format by default. A printer control footer ends the image file. OPTIONS
-raw If specified, each pixel will be explicitly described in the image file. If -raw is not specified, output will default to com- pressed format in which identical adjacent pixels are replaced by "repeat pixel" commands. A raw file is often an order of magni- tude larger than a compressed file and prints much slower. -margin If -margin is not specified, the image will be start at the left margin (of the window, paper, or whatever). If -margin is speci- fied, a 1.5 inch left margin will offset the image. PRINTING
Generally, sixel files must reach the printer unfiltered. Use the lpr -x option or cat filename > /dev/tty0?. BUGS
Upon rescaling, truncation of the least significant bits of RGB values may result in poor color conversion. If the original PPM maxval was greater than 100, rescaling also reduces the image depth. While the actual RGB values from the ppm file are more or less retained, the color palette of the LJ250 may not match the colors on your screen. This seems to be a printer limitation. SEE ALSO
ppm(5) AUTHOR
Copyright (C) 1991 by Rick Vinci. 26 April 1991 ppmtosixel(1)
All times are GMT -4. The time now is 05:14 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy