extract raw image data but result is out of expect - c++

I am using C++ to extract the raw image data.
But here comes a trouble.
I use either fseek or fread functions to move the file pointer, but both results are out of my expectation.
It seems the pointer is not the location which I want to move to.
Could someone give me a hint?
#include <stdio.h>
#include <stdlib.h>
int IMAGE_WIDTH=1280;
int IMAGE_HEIGHT=800;
int size=1280*800*2;
int header=128;
int line_padding=0;
int main()
{
FILE* fd;
FILE* fd_bin;
char *temp = (char*)malloc(size);
char *dat = (char*)malloc(size);
if (!dat) {
perror("malloc");
return NULL;
}
fd = fopen("original.raw", "rb");
if (!fd) {
printf("File Read Fail...\n");
exit(1);
}
// fseek(fd, header, SEEK_SET);
fread(temp, 1, header, fd);
for(int k=0;k<IMAGE_HEIGHT;k++)
{
fread(dat, 1, IMAGE_WIDTH*2, fd);
//fseek(fd , line_padding*2, SEEK_CUR);
fread(temp, 1, line_padding*2, fd);
}
/////////////////////////////Save bin
fd_bin = fopen("output.raw", "wb");
if (!fd_bin) {
printf("File Open Fail...\n");
exit(1);
}
fwrite( dat, 1, IMAGE_WIDTH*IMAGE_HEIGHT*2, fd_bin);
fclose(fd_bin);
///////////////////////////////////////////
fclose(fd);
free(temp);
free(dat);
}

Related

Cant copy the whole text file to char array

I am trying to copy a whole text file into char array using fstream but even upon increasing the size of the array it reads the text file to same limit .i am bount to save it in a char array and it will be good if it is not a dynamic one ??? any solution please ...
// smallGrams.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
void readInput(const char* Path);
void removePunctucationMarks();
void removeSpacing();
void insertDots();
char * getText();
void generateUnigrams();
void generateBigrams();
void generateTrigrams();
double validateSentance(string str);
string sentenceCreation(int position);
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}
void readInput(const char* Path)
{
ifstream infile;
infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else
cout<<"File failed to open"<<endl;
int arrSize=100000000;
char *arr=new char[arrSize];
int i=0;
while(!infile.eof()&&i<arrSize)
{
infile.get(arr[i]);
i++;
}
arr[i-1]='\0';
for(short i=0;i<arrSize&&arr[i]!='\0';i++)
{
cout<<arr[i];
}
}
This is a C style solution that works. It checks the file size and then allocate the necessary memory for the array and reads all the content of the file in one call. The fread() call returns the number of bytes you requested or an error has ocurred (check fread() reference)
# include <cstring>
# include <cstdlib>
# include <cstdio>
int main(int argc, char *argv[]) {
char *data;
int data_len;
FILE *fd;
fd = fopen ("file.txt", "r");
if (fd == NULL) {
// error
return -1;
}
fseek (fd , 0 , SEEK_END);
data_len = ftell (fd);
rewind (fd);
data = (char *) malloc ((data_len + 1) * sizeof (char));
memset (data, data_len + 1, NULL);
if (fread (data, sizeof (char), data_len, fd) != data_len) {
// error
return -1;
}
printf ("%s\n", data);
fclose (fd);
free (data);
return 0;
}
Here with a simple doubling method...
#include<iostream>
#include<string>
#include<fstream>
#include <cstdint>
#include <cstring>
using namespace std;
void readInput(const char* Path)
{
ifstream infile;
infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else{
cout<<"File failed to open"<<endl;
return;
}
int capacity=1000;
char *arr=new char[capacity];
char *temp;
int i=0;
while(infile >> arr[i])
{
i++;
if ( i >= capacity ) {
temp = new char[capacity*2];
std::memcpy(temp , arr, capacity);
delete [] arr;
arr = temp;
capacity *=2;
}
}
}
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}
The error could when you read and display the array content using the for loop and not on reading the data from file.
Use int instead of short in for loop, as short can increment upto 32768, only.

C++ reading a file prints nothing to console

I'm having trouble printing the contents of a file to console.
file.bin contents are "abc".
data holds value, but it just doesn't print it...
#include <Windows.h>
#include <iostream>
int main()
{
wchar_t *data;
FILE* file;
int err = _wfopen_s(&file, L"file.bin", L"rb");
if (err != 0)
{
std::cout << "Error";
return 0;
}
fseek(file, 0, SEEK_END);
long lSize;
lSize = ftell(file);
rewind(file);
data = (wchar_t *)malloc(lSize + 1);
fread(data, 1, lSize, file);
//dereference pointer
wchar_t data2 = *data;
std::wcout << data2; // prints nothing...
system("PAUSE");
return 0;
}
EDIT
I know about fstream but I would really prefer C style opening/reading files.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::ifstream ifs("file.bin");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
std::cout<<content;
return 0;
}
Use std::ifstream if you're using c++. You're making this much more complicated then you need to. See this former answer.

Printing array of char pointers

I am trying to read two lines from a file using array of pointers. However, I am not getting anything on screen. I have tried searching online, but could not solve the problem. Here is my code that I have written using Netbeans on mac.
int main(int argc, char** argv) {
FILE *fp;
char *points[50];
char c;
int i=0;
fp=fopen("/Users/shubhamsharma/Desktop/data.txt","r");
if(fp==NULL)
{
printf("Reached here");
fprintf(stderr," Could not open the File!");
exit(1);
}
c=getc(fp);
while(c!=EOF)
{
*points[i]=c;
c=getc(fp);
i++;
}
for(int i=0;*points[i]!='\0';i++)
{
char d=*points[i];
printf("%c",d);
if(*(points[i+1])==',')
{
i=i+1;
}
}
return (EXIT_SUCCESS);
}
char *points[50];
Is not what you want, this is an array of 50 pointers to char.
If you want an array of pointers to char[50] you need:
char (*points)[50];
points = malloc(sizeof(*points) * 2);
Also note that fgets is prefered to get a line from a file
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char (*points)[50];
points = malloc(sizeof(*points) * 2);
if (points == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
fgets(points[0], sizeof(*points), fp);
fgets(points[1], sizeof(*points), fp);
fclose(fp);
printf("%s", points[0]);
printf("%s", points[1]);
free(points);
return 0;
}

reading a .txt save file in CPP and save the value to local variable

i'm new in C++ (and file input output), I learned how to use fprint to print something from a .txt in a formatted style, but how do I search for a certain value and save that value in a local variable? below is the code for save:
void savestate(state a){ //state is a struct with data I need such as position etc
FILE * save;
int data[]= { a.level, a.goalX, a.goalX, a.monX, a.monY };
save = fopen("game.txt", "wb"); // << might have to use suggestion C
fwrite(data, sizeof(int), sizeof(data), save); // is this actually the correct way to do it?
fclose(save);
}
as for load, I'm stuck with this:
void loadstate(){
FILE* save;
save = fopen("game.txt", "rb");
if(save== NULL) perror("no savegame data");
else{
// don't even know what function I should use
}
and by the way, after I activate the save function, the game.txt is not in a quite readable format. I can open in in my notepad, but it shows something like ÌÌÌÌÌÌÌÌøäÁ_ÌÌÌÌúƒ which makes no sense. any idea? :D
Use text file for this purpose, not a binary file. The saveData function
will create the data.txt file and then the function loadData reads the data from the file. I you want some more explanation leave a comment below.
#include <stdio.h>
#include <stdlib.h>
void saveData() {
FILE* f = fopen("data.txt", "w");
if(f == NULL) {
printf("cant save data");
return;
}
//write some data (as integer) to file
fprintf(f, "%d %d %d\n", 12, 45, 33);
fprintf(f, "%d %d %d\n", 1, 2, 3);
fprintf(f, "%d %d %d\n", 9, 8, 7);
fclose(f);
}
void loadData() {
int data1, data2, data3;
FILE* f = fopen("data.txt", "r");
if(f == NULL) {
printf("cant open file");
return;
}
//load data from file, fscanf return the number of read data
//so if we reach the end of file (EOF) it return 0 and we end
while(fscanf(f, "%d %d %d", &data1, &data2, &data3) == 3) {
printf("data1 = %d data2 = %d data3 = %d\n", data1, data2, data3);
}
fclose(f);
}
int main() {
saveData();
loadData();
return 0;
}
example of writing to a file:
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
int i = 78;
string word = "AWord";
ofstream fout("AFile", ios_base::out | ios_base::binary | ios_base::trunc);
fout << i;
fout << endl;
fout << word;
fout.close();
return 0
}
example of reading from a file :
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
int ix;
string wordx;
ifstream fin("AFile", ios_base::in | ios_base::binary);
fin >> ix;
while(fin.get() != '\n'){
fin.get();
}
fin >> wordx;
fin.close();
return 0
}

programming c threaded io

Hi what i want to do is read from a text file do something to the text and write it back out to a file. I need it to be threaded so all 3 party can run at the same time. I am trying to use a buffer to read in to and a buffer to write out from but cant work it out.
My code :
#include <stdio.h>
#include <pthread.h>
char inBuf[1000];
//char outBuf[];
void *readerFun(void *meg){
char *inputFile;
FILE *input_ptr;
inputFile = (char *) meg;
input_ptr = fopen(inputFile, "r");
if(input_ptr == NULL){
printf("%s\n", inputFile);
printf("input file not working\n");
return;
}
while(!feof(input_ptr)){
fscanf(input_ptr, "%s", &inBuf);
sleep(1);
// printf("%s\n", &inBuf );
// printf("test _____________\n" );
}
return NULL;
}
void *modifierFun(void *meg){
//char c;
//while((c = getc(inBuf) != EOF)){
//strcat(outBuf, c);
//}
//}
return NULL;
}
void *writerFun(void *meg){
char *outFile;
FILE *output_ptr;
outFile = (char *) meg;
output_ptr = fopen(outFile, "a");
while(inBuf != NULL){
printf("%s\n", inBuf );
fprintf(output_ptr, "%s", inBuf);
}
return NULL;
}
int
main (int argc, char **argv){
pthread_t reader, modifier, writer;
char *meg = argv[1];
char *meg2 = argv[2];
int ret1, ret2, ret3;
ret1 = pthread_create(&reader, NULL, readerFun, (void *) meg);
ret2 = pthread_create(&modifier, NULL, modifierFun, (void *) meg);
ret3 = pthread_create(&writer, NULL, writerFun, (void *) meg2);
pthread_join(reader, NULL);
pthread_join(modifier, NULL);
pthread_join(writer, NULL);
return 0;
}
Would be a big help is someone could point me down the right road. I have looked all over the net and cant really find what im looking for.