Loading a file that contains hex values into a char array - c

this may seem basic to some of you, but please try to help me!
I have created a BMP file that stores a 4 x 3 image. The content of this file (FILEHEADER, FILEINFOHEADER, color bytes, and padding, are represented in hex).
I'm trying to write a loadFile function to load the BMP file and store it into a 2D array of integers.
I'm first trying to figure out how to store the content of the file into a character array, then i would try and do a strcpy of the char array and convert that into int values (i'm not converting yet).
But for now i've attempted to load the file and put into a char array... (it doesn't work, but i was hoping to get some feedback on whether or not i'm in the right direction), and how would i go about approaching this problem!
#include <stdio.h>
#include <stdlib.h>
#define length 30
#define rows 7
int main()
{
FILE *myBmp;
myBmp = fopen("myBmp.bmp", "r"); //for now i'm not sure what the r is for
//read file into array
char hexArray[rows][length];
int c;
for (c = 0; c < rows; c++) {
fscanf(myBmp, "%c", &hexArray[c]);
}
for (c = 0; c < rows; c++) {
printf("Number is: %c\n", hexArray[c]);
}
fclose(myBmp);
}

Related

Convert buffer to array of 8-bit values and back in C

I would like to write a program in C that gets the file content via stdin and reads it line by line and, for each line, converts it to an array of 8-bit integer values.
I also would like to be able to do the reverse process. After working with my array of 8-bit values, I would like to convert it again to "lines" that would be organized as a new buffer.
So basically, I would like to convert a char * line to an int array[] and back (an int array[] to a char * line) while keeping the consistency, so when I create the file again out of the conversions, the file is valid (and by valid I mean, the conversion from int array[] to char * line generates the same content of the original char * line, while reading each line of the stdin.
My code is currently as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read;
stream = stdin;
if (stream == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, stream)) != -1) {
char * array = line_to_array(line);
// here I include the rest of my code
// where I am going to use the generated array
// ...
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}
The line_to_array function would be the one to convert the "line" content to the array of integers. In a second file, I would just do the opposite.
The mechanics of the process would be like this:
The first program (first.c) would receive a file content via stdin. By reading it using getline, I would have each line to convert to an array of integers and send each line to a second program (second.c) that would convert each array to a char * buffer again and the reconstruct the file.
In the terminal, I would run it like this:
./first | ./second
I appreciate any help on this matter.
Thank you.
I believe you may already know that a name of array is a kind of constant pointer. You could verify the fact from following code:
char hello[] = "hello world!";
for( int idx=0; *(hello + idx) != 0; idx++ )
{
printf("%c", *(hello + idx));
}
printf("\n");
So, there are no reason to convert character pointer to array. For your information, A char variable is a 8bit data in C, this can contain a integer value which is represent a character: 65 represent 'A' in ASCII code.
Secondly, this link may help you to understand how to convert between c string and std::string.
On second thought, may your input file is UNICODE or UTF-8 encoded file which is using multi-byte character code. In that case, you may not able to use getline() to read the string from the file. If so, please refer this question: Reading unicode characters.
I wish following code assist you to understand char type, array and pointer in C/C++:
std::string hello("Hello world");
const char *ptr = hello.c_str();
for( int idx=0; idx < hello.size(); idx++ )
{
printf("%3d ", *(ptr + idx));
}
printf("\n");
std::string hello("Hello world");
const char *ptr = hello.c_str();
for( int idx=0; idx < hello.size(); idx++ )
{
printf("%3d ", ptr[idx]);
}
printf("\n");

Correctly store content of file by line to array and later print the array content

I'm getting some issues with reading the content of my array. I'm not sure if I'm storing it correctly as my result for every line is '1304056712'.
#include <stdio.h>
#include <stdlib.h>
#define INPUT "Input1.dat"
int main(int argc, char **argv) {
int data_index, char_index;
int file_data[1000];
FILE *file;
int line[5];
file = fopen(INPUT, "r");
if(file) {
data_index = 0;
while(fgets(line, sizeof line, file) != NULL) {
//printf("%s", line); ////// the line seems to be ok here
file_data[data_index++] = line;
}
fclose(file);
}
int j;
for(j = 0; j < data_index; j++) {
printf("%i\n", file_data[j]); // when i display data here, i get '1304056712'
}
return 0;
}
I think you need to say something like
file_data[data_index++] = atoi(line);
From your results I assume the file is a plain-text file.
You cannot simply read the line from file (a string, an array of characters) into an array of integers, this will not work. When using pointers (as you do by passing line to fgets()) to write data, there will be no conversion done. Instead, you should read the line into an array of chars and then convert it to integers using either sscanf(), atoi() or some other function of your choice.
fgets reads newline terminated strings. If you're reading binary data, you need fread. If you're reading text, you should declare line as an array of char big enough for the longest line in the file.
Because file_data is an array of char, file_data[data_index] is a single character. It is being assigned a pointer (the base address of int line[5] buffer). If reading binary data, file_data should be an array of integers. If reading strings, it should be an array of string, ie char pointers, like char * file_data[1000]
you also need to initialize data_index=0 outside the if (file) ... block, because the output loop needs it to be set even if the file failed to open. And when looping and storing input, the loop should test that it's not reached the size of the array being stored into.

program in C language calculates the number of repeat words

I have a text file containing 5 words, and the second text file containing 2000 words I want to write a program in C language calculates the number of repeat words from first file in the second file and print the result on screen and I am new in C language , can any one help me to do it ...Thank you
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_line(FILE *in, char *buffer, size_t max)
{
return fgets(buffer, max, in) == buffer;
}
int main(void)
{
char b[2000];
int wcount = 0;
int j;
char i[5];
char File_path[40];
char stuff[5] = "False";
FILE *file1;
FILE *file2;
file1=fopen("test.txt", "r"); // my word list text file
file2=fopen("dickens-chimes-379.txt","r"); // my text file
for (j = 0; j < 5 && strcmp(i, stuff); j++)
{
fscanf(file1,"%s",i);
while (fgets(b,2000, file2)!=NULL)
{
if((strcat(b,i)) ==NULL)
{
wcount=0;
}
wcount++;
}
printf("%s %d\n",i,wcount);
wcount=0;
}
fclose(file1);
fclose(file2);
}
my input is (test.txt) have words (love,like,book,go, and test)
the output is love 4296 like 0 book 0 go 0 test 0
i need the real value of the words occurrence in file2
i found this code in the net and i don't know how to modify it because
i an new to c language .. i hope you could help to to write code for
same thing
I feel to mention that this is a fairly complicated problem for a beginner. I would suggest to get warmed up with simpler problems first.
Nevertheless, here are some high level thoughts:
Separate I/O from business logic
Read test.txt in a array of 5 words
Read a dickens.txt in a character array.
[If the file is really really big, then this strategy may need to be modified.]
Pass the test array and dickens array to the core function, say repeatFinder()
Very very high level pseudocode:
for each word w in test array:
scan dickens array
if w occurs in dickens:
w_counter +=1
advance dickens array
In C, you can use strstr( dickens, w ) [link] to find if w is present in dickens

Read CSV into array to sort numerically by numbers given in the lines

I try to read a temporary file consisting of several lines like the following example. The lines are NOT sorted.
3;NOK
2;OK
1;NA
For an easy output-function, in which I want to offer several possibilities of output (CSV, Print on Screen...), I thought it would be clever to do the following.
Open the file
Iterate through the lines
Extract the number at the beginning
Use this as index of an array
The result should be a "sorted" array
A minimal example which gives me an Segmentation Fault.
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[]){
FILE *outfp = fopen("test.txt", "r");
if (outfp == NULL){
printf("There was a problem: Temporary output-file could not be opened");
return 1;
}
// OUTPUT HANDLING
char output_line[1024];
char output_cut[1024];
int line_number;
char *output_array[3]; //The maximum number of possible entries is fixed
// I got variables for the line, for the linenumber and output_cut is needed for sscanf
while(fgets(output_line, sizeof(output_line), outfp)!=NULL){
sscanf(output_line,"%d;%s",&line_number,output_cut);
output_array[line_number]=output_line;
}
printf("LINE1:%s",output_array[1]);
printf("LINE2:%s",output_array[2]);
printf("LINE3:%s",output_array[3]);
return 0;
}
My first question: Is this the right way to do, or are there other better ways to "sort" this kind of file in an easy way for flexible output?
If yes, why does this not work?
Regards
Markus
Edit: the example textfile just contains numbers from 1-3... not 13,14...
Edit2: the solution
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]){
FILE *outfp = fopen("test.txt", "r");
if (outfp == NULL){
printf("There was a problem: Temporary output-file could not be opened");
return 1;
}
// OUTPUT HANDLING
char output_line[1024];
char output_cut[1024];
int line_number;
char output_array[4][1024]; //The maximum number of possible entries is fixed
// I got variables for the line, for the linenumber and output_cut is needed for sscanf
while(fgets(output_line, sizeof(output_line), outfp)!=NULL){
sscanf(output_line,"%d;%s",&line_number,output_cut);
strcpy(output_array[line_number],output_line);
}
printf("LINE1: %s",output_array[1]);
printf("LINE2: %s",output_array[2]);
printf("LINE3: %s",output_array[3]);
return 0;
}
You have two major problems with the code as shown in the question. The first is that all the pointers in the output_array points to the same place. This means that when you print the lines all will print the same (which will be the last line read).
The second problem is your array indexing. Array indices goes from zero to the size minus one, so for your output_array the indices are 0 to 2 (inclusive). The problem causing the crash is that you use index 3 which is out of bound for the array, and leads to undefined behavior.

read the header of a .pgm image file

I am attempting to read the size values from the header of a .pgm image file (mars.pgm), and assign the resulting values to the integer variables u and v using sscanf.
When executed the program prints P5 832 700 127 in the first line, which is correct (the 832 and 700 are the size values that I want to pick out).
In the second line that is meant to print u and v variables two very large numbers are printed, instead of the 832 and 700 values.
I cannot figure out why this is not working as desired. When using the small test program (located at the bottom of the post) sscanf picks out the values from a string like I expected it to.
#include<stdio.h>
#include <string.h>
int main()
{
FILE *fin;
fin= fopen ("mars.pgm","r+");
if (fin == NULL)
{
printf ("ERROR");
fclose(fin);
}
int u,v,i,d,c;
char test[20];
for (i=0; i<=20; i++)
{
test[i]=getc(fin);
}
sscanf(test,"%d,%d,%d,%d",&c,&u,&v,&d);
printf("%s\n",test);
printf("%d %d",u, v);
fclose(fin);
}
small test Program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(void)
{
int a;
char s[3];
s[0]='1';
s[1]=' ';
s[2]='2';
sscanf(s,"%d",&a);
printf("%d",a);
}
First of all, I advise you to make a small test: initialize your variables with a 0, for instance, and verify what value they are holding after read operation.
Then, try removing , characters from your format string. Check if it works then.
This behavior you see is happening because fscanf() and derivatives match the full pattern when scanning, which means if your source data has no commas and your format has commas, it may be ignored.

Resources