I tried to run this program through the terminal and this error showed up.
"Segmentation Fault: 11"
I would like to know why . What this program does is, it reads a .ppm file and it saves it's information in a matrix variable of type Pixel, so, a PPM file is basically composed by: the first line is going to be "P3" by default, second line the size of the matrix, and the third line the highest value possible for a Pixel attribute, the other lines will have 3 integers of maximum value of 255, so for each member of the matrix there will be a pixel R, G, B.
what I tried to do in the function save_image, first recognize if we are dealing with a ppm file(checking if there is a P3 in the first line), then read the number of rows and columns for the matrix, then it creates a new matrix using the malloc function, then it will save the data in the lines of the file to the .r and .g and .b of the variable myImg.
I am very new to debugging/programming so I'm sorry if this isn't enough information but I tried my best.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int r;
int g;
int b;
}Pixel;
void save_image(FILE* img, Pixel ** newImg) {
int i;
int j;
int fcount;
int scount;
int count;
int dcc;
char init[3];
fscanf(img,"%s",init);
if(init[0]=='P' && init[1]=='3'){
printf("worked!\n");
fscanf(img,"%d %d",&j,&i);
fscanf(img, "%d",&dcc);
*newImg = (Pixel*)malloc(sizeof(Pixel) * i);
for ( count = 0; count < i ; ++count)
{
newImg[count] = (Pixel*)malloc(sizeof(Pixel) * j);
}
for (fcount = 0; fcount <= i ; ++fcount)
{
for (scount = 0; scount <= j; ++scount)
{
fscanf(img,"%i %i %i",&newImg[i][j].r,&newImg[i][j].g,&newImg[i][j].b);
}
}
}
else
printf("Type of file not recognized\n");
fclose(img);
}
int main(int argc, char const *argv[])
{
FILE* image;
Pixel myImg;
Pixel** newImg;
**newImg = myImg;
image = fopen(argv[1],"r");
save_image(image,newImg);
return 0;
}
The program fails because the initial malloc for newImg[] is malloc'ing some multiple of the size of Pixel rather than size of pointer to Pixel combined with problems with the passing of the pointer to the newImg as a parameter to the save_image() function. See my comment about where the variable newImg should be defined and the desirable modification to the declaration of the save_image() function
Given the was the posted code is written, it seems to be expecting the 'plain' .ppm file format
and the posted code is failing to allow for any embedded comments within the file
given this description of the format of a .ppm file:
The format definition is as follows. You can use the libnetpbm C subroutine library to read and interpret the format conveniently and accurately.
A PPM file consists of a sequence of one or more PPM images. There are no data, delimiters, or padding before, after, or between images.
Each PPM image consists of the following:
A "magic number" for identifying the file type. A ppm image's magic number is the two characters "P6".
Whitespace (blanks, TABs, CRs, LFs).
A width, formatted as ASCII characters in decimal.
Whitespace.
A height, again in ASCII decimal.
Whitespace.
The maximum color value (Maxval), again in ASCII decimal. Must be less than 65536 and more than zero.
A single whitespace character (usually a newline).
A raster of Height rows, in order from top to bottom. Each row consists of Width pixels, in order from left to right. Each pixel is a triplet of red, green, and blue samples, in that order. Each sample is represented in pure binary by either 1 or 2 bytes. If the Maxval is less than 256, it is 1 byte. Otherwise, it is 2 bytes. The most significant byte is first.
A row of an image is horizontal. A column is vertical. The pixels in the image are square and contiguous.
In the raster, the sample values are "nonlinear." They are proportional to the intensity of the ITU-R Recommendation BT.709 red, green, and blue in the pixel, adjusted by the BT.709 gamma transfer function. (That transfer function specifies a gamma number of 2.2 and has a linear section for small intensities). A value of Maxval for all three samples represents CIE D65 white and the most intense color in the color universe of which the image is part (the color universe is all the colors in all images to which this image might be compared).
ITU-R Recommendation BT.709 is a renaming of the former CCIR Recommendation 709. When CCIR was absorbed into its parent organization, the ITU, ca. 2000, the standard was renamed. This document once referred to the standard as CIE Rec. 709, but it isn't clear now that CIE ever sponsored such a standard.
Note that another popular color space is the newer sRGB. A common variation on PPM is to substitute this color space for the one specified.
Note that a common variation on the PPM format is to have the sample values be "linear," i.e. as specified above except without the gamma adjustment. pnmgamma takes such a PPM variant as input and produces a true PPM as output.
Strings starting with "#" may be comments, the same as with PBM.
Note that you can use pamdepth to convert between a the format with 1 byte per sample and the one with 2 bytes per sample.
All characters referred to herein are encoded in ASCII. "newline" refers to the character known in ASCII as Line Feed or LF. A "white space" character is space, CR, LF, TAB, VT, or FF (I.e. what the ANSI standard C isspace() function calls white space).
Plain PPM
There is actually another version of the PPM format that is fairly rare: "plain" PPM format. The format above, which generally considered the normal one, is known as the "raw" PPM format. See pbm for some commentary on how plain and raw formats relate to one another and how to use them.
The difference in the plain format is:
There is exactly one image in a file.
The magic number is P3 instead of P6.
Each sample in the raster is represented as an ASCII decimal number (of arbitrary size).
Each sample in the raster has white space before and after it. There must be at least one character of white space between any two samples, but there is no maximum. There is no particular separation of one pixel from another -- just the required separation between the blue sample of one pixel from the red sample of the next pixel.
No line should be longer than 70 characters.
Here is an example of a small image in this format.
P3
# feep.ppm
4 4
15
0 0 0 0 0 0 0 0 0 15 0 15
0 0 0 0 15 7 0 0 0 0 0 0
0 0 0 0 0 0 0 15 7 0 0 0
15 0 15 0 0 0 0 0 0 0 0 0
There is a newline character at the end of each of these lines.
Programs that read this format should be as lenient as possible, accepting anything that looks remotely like a PPM image.
Related
I wrote this function that performs a slightly modified variation of run-length encoding on text files in C.
I'm trying to generalize it to binary files but I have no experience working with them. I understand that, while I can compare bytes of binary data much the same way I can compare chars from a text file, I am not sure how to go about printing the number of occurrences of a byte to the compressed version like I do in the code below.
A note on the type of RLE I'm using: bytes that occur more than once in a row are duplicated to signal the next-to-come number is in fact the number of occurrences vs just a number following the character in the file. For occurrences longer than one digit, they are broken down into runs that are 9 occurrences long.
For example, aaaaaaaaaaabccccc becomes aa9aa2bcc5.
Here's my code:
char* encode(char* str)
{
char* ret = calloc(2 * strlen(str) + 1, 1);
size_t retIdx = 0, inIdx = 0;
while (str[inIdx]) {
size_t count = 1;
size_t contIdx = inIdx;
while (str[inIdx] == str[++contIdx]) {
count++;
}
size_t tmpCount = count;
// break down counts with 2 or more digits into counts ≤ 9
while (tmpCount > 9) {
tmpCount -= 9;
ret[retIdx++] = str[inIdx];
ret[retIdx++] = str[inIdx];
ret[retIdx++] = '9';
}
char tmp[2];
ret[retIdx++] = str[inIdx];
if (tmpCount > 1) {
// repeat character (this tells the decompressor that the next digit
// is in fact the # of consecutive occurrences of this char)
ret[retIdx++] = str[inIdx];
// convert single-digit count to string
snprintf(tmp, 2, "%ld", tmpCount);
ret[retIdx++] = tmp[0];
}
inIdx += count;
}
return ret;
}
What changes are in order to adapt this to a binary stream? The first problem I see is with the snprintf call since it's operating using a text format. Something that rings a bell is also the way I'm handling the multiple-digit occurrence runs. We're not working in base 10 anymore so that has to change, I'm just unsure how having almost never worked with binary data.
A few ideas that can be useful to you:
one simple method to generalize RLE to binary data is to use a bit-based compression. For example the bit sequence 00000000011111100111 can be translated to the sequence 0 9623. Since the binary alphabet is composed by only two symbols, you need to only store the first bit value (this can be as simple as storing it in the very first bit) and then the number of the contiguous equal values. Arbitrarily large integers can be stored in a binary format using Elias gamma coding. Extra padding can be added to fit the entire sequence nicely into an integer number of bytes. So using this method, the above sequence can be encoded like this:
00000000011111100111 -> 0 0001001 00110 010 011
^ ^ ^ ^ ^
first bit 9 6 2 3
If you want to keep it byte based, one idea is to consider all the even bytes frequencies (interpreted as an unsigned char) and all the odd bytes the values. If one byte occur more than 255 times, than you can just repeat it. This can be very inefficient, though, but it is definitively simple to implement, and it might be good enough if you can make some assumptions on the input.
Also, you can consider moving out from RLE and implement Huffman's coding or other sophisticated algorithms (e.g. LZW).
Implementation wise, i think tucuxi already gave you some hints.
You only have to address 2 problems:
you cannot use any str-related functions, because C strings do not deal well with '\0'. So for example, strlen will return the index of the 1st 0x0 byte in a string. The length of the input must be passed in as an additional parameter: char *encode(char *start, size_t length)
your output cannot have an implicit length of strlen(ret), because there may be extra 0-bytes sprinkled about in the output. You again need an extra parameter: size_t encode(char *start, size_t length, char *output) (this version would require the output buffer to be reserved externally, with a size of at least length*2, and return the length of the encoded string)
The rest of the code, assuming it was working before, should continue to work correctly now. If you want to go beyond base-10, and for instance use base-256 for greater compression, you would only need to change the constant in the break-things-up loop (from 9 to 255), and replace the snprintf as follows:
// before
snprintf(tmp, 2, "%ld", tmpCount);
ret[retIdx++] = tmp[0];
// after: much easier
ret[retIdx++] = tmpCount;
My code requires me to open up a file.
the first line of the file contains 2 integers between 1 and 1000.
I must read these 2 numbers, use them to create a 2D array corresponding to those numbers
(e.g. 50,200 is - array[50][200]).
After i have created this array, i have to read the rest of the file and store the data (which is set up in a grid of the dimensions of the 2 numbers).
What is the best way to go about this. I thought about doing a getline and then doing a for loop to append the chars to row then column and then converting to int, but my compiler kept coming up with errors.
Is the file binary or text? If binary, use fread, it will let you read the raw bytes easily. if its text use fscanf
Assuming the input is always of this form (a little unclear):
2,4
aaaa
b b
... then an approach would be to read in the dimensions of your matrix (number of rows, number of columns) and then follow that up by reading each element of the matrix one character at a time. It would be something along the lines of this:
int rows = getchar();
// Skip ','.
getchar();
int cols = getchar();
int arr[ rows ][ cols ];
int r = 0;
int c = 0;
for ( int byte = getchar(); byte != EOF; byte = getchar(), c++ ) {
if ( c == cols ) {
c = 0;
r++;
}
arr[ r ][ c ] = byte;
}
... and you would need to pipe the input file to your program as follows:
./program.out < input.txt
Remark: This is tailored to your specific problem-set, it would not work if: the input is not guaranteed to populate the entire array, the input is a bad size, overflow of dimensions, etc. (many issues) - so be sure to account for those.
I am displaying a partition table, and the table is displayed somewhat like:
Number Device name Partition type Size in MB
------------------------------------------------------------
1 /dev/sda1 NTFS 300
2 /dev/sda2 *Win95 FAT32 99
3 /dev/sda3 Unknown 128
4 /dev/sda4 NTFS 19472
120 /dev/sda120 NTFS 3000
*=Active partition
Now for displaying the above, we are using formatted output printf and the format string is
"%-6d=partition number %-25.25s=device name %c=active partition %-30.30s=part type %7Ld=size"
Now i want to display the same partition table, but with some slight modification, such that the gaps in partition slots would be displayed by a range, like:
5-119 /dev/sda5.../dev/sda119 Empty 0
I am using the formatted string as:
%d-%-6d=partition range %s%d...%s%d=(/dev/sda5.../dev/sda119) %c %-30.30s %7Ld
but it does not help me.
What should be the correct format string? I am using a gcc compiler.
I think you need to use snprintf() to prepare the two composite strings, and then a simpler printf() to do the actual printing. Since you've not shown your actual code, we have to guess at everything, which is a nuisance...
int min = 5;
int max = 119;
char *dev = "/dev/sda";
char num_range[32];
char dev_range[60];
snprintf(num_range, sizeof(num_range), "%d-%d", min, max);
snprintf(dev_range, sizeof(dev_range), "%s%d...%s%d", dev, min, dev, max);
printf("%-10s %-50.50s %c%-30.30s %7d", num_range, dev_range, ' ', "Empty", 0);
You specified %-25.25s for a single device, so it isn't clear whether you should double that for the range, or you should use some other value (or even the same value); you'll need to tweak that part of the format string to suit yourself. This technique is also how I get a colon at the end of a name — format the name and the colon into a string, and then format that string into the final print operation.
I am trying to read pixel data from a PPM file. I have a function to read the header so I know it's pointing to the beginning of the pixel data. I tried using fgetc(file) but if the value is more than one digit it will not work. I also tried using an array and converting the array to an int or char but I have no way of knowing how many digits each value is. I'm also not sure if the values are separated by whitespace or not. Basically I need a way to extract the pixel data. (I'm using C.)
My code right now is:
char read_byte(FILE *ipt) {
int c, i=0, sum=0;
while (i<16) {
c=fgetc(ipt);
if((i%2)!=0 {
if(c&1) {
sum+=pow(2,i/2);
}
}
i++;
}
return (char)sum;
}
EDIT:
At first I thought the file was stored as the ASCII values, then I realized it's stored as binary. Right now I think I'm making it act like hex. I'm not sure if that's correct. I'm really stuck.
EDIT: changed my code a bit
char read_byte(FILE *ipt) {
int c, i=0, sum=0;
while(i<8) {
c = fgetc(ipt);
c=c&1;
sum+=c*pow(2,i);
i++;
}
return sum;
}
I print the sum as %c
Must you write this for an assignment, or is it for pleasure, or could you use someone else's code?
There is an Open Source solution.
"Netpbm is a package of graphics programs and a programming library. " which includes programs to read PPM at http://netpbm.sourceforge.net/doc/
Edit:
Have you got, or read the definition of the file format, e.g. http://netpbm.sourceforge.net/doc/ppm.html?
It looks like the data is either sequences of one byte RGB triples, or sequences of two byte RGB triples.
The program can detect which format is used from item 7 "The maximum color value (Maxval)". It says "If the Maxval is less than 256, it is 1 byte. Otherwise, it is 2 bytes."
So you code a function which reads one byte/component RGB data, then code another to read two byte/component RGB data.
The program can choose which to call once it has read the value of Maxval.
Edit {
According to the document at that link, the image data in a 'P6' ppm is binary.
So if MaxValue is <256, and hence the data for each colour component is one byte, then reading three bytes, with three calls of fgetc(fp) would return the binary value of one RGB pixel.
If the program has read the header, it has the values of width and height for the image data. So it could allocate an array for every row (width wide of RGB pixels), and an array of pointers to each allocated pixel row array. Then read the binary data into each row, and the program has something straightforward to operate on; a 2d array.
} end edit
My reading of your question suggests you already know how to read one byte data using fgetc.
Edit - it seems like this is irrelevant:
You can read two byte data by calling fgetc twice, and shifting and bit or-ing the data, e.g. (partly ignoring error checking):
int a = fgetc(fp);
int b = fgetc(fp);
if (a >= 0 && b >= 0) { // then all is okay
unsigned int twobyte = (a<<8) | b; // or (b<<8) | a; depending on byte order
// ...
I am trying to read a block which contains block bitmap and inode bitmap
I read a block as a unsigned char array
than I convert it to binary as follows:
for (i = 0; i < 4096; i++) {
for (j = 8; j <=0 ; j--) {
bits[j] = bitmap[i]%2;
bitmap[i] = bitmap[i]/2;
}
for(t=0; t<8;t++)
printf("%d\t",bits[t]);
printf("\n");
}
when I put '0' to char and print it as
printf("%d",'0');
I get 48
and my bits array contains 00110000
That works, however when I check inode bitmap
it does not work
for example a bitmap is:
1 1 1 0 0 0 0
but I get
0 0 0 0 1 1 1
I could not check if same thing happens with block bitmap.
To repeat, the code works normal conversation for example it prints 00110000 which is 48, for char '0' which print 48 also. This swapping occurs with inode bitmap.
When I change for it will work for inode bitmap but how can I now it will work for blok bitmap. This will fix the code but the logic is wrong.
Any idea?
The lines
for(t=0; t<8;t++)
printf("%d\t",bits[t]);
print the bit at position 0 (the least significant one) first and the bit at position 7 (the most significant) last. As you want it to be the other way around, change the loop to:
for(t=7; t>=0;t--)
or similar.
looks like your bit order is swapped
big-endian vs little endian.
http://en.wikipedia.org/wiki/Endianness
you can swap with htonl, htons, ntohl, ntohs family of functions. try man htons.
or run your loop in reverse.