I have followed this tutorial:http://dranger.com/ffmpeg/tutorial01.html for using ffmpeg in android studio using android NDK.
I have made some minor correction as some functions used here are depreciated now.Here's my code can anyone point out whats wrong with my code as i am getting errorand couldn't find out what's wrong
#include <jni.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame);
JNICALL
JNIEXPORT jstring
Java_com_viralsam_root_tester_MainActivity_trtest(JNIEnv *env, jobject obj , jint argc,
jstring argv_){
const char *name;
int i,videostream;
name= (*env)->GetStringUTFChars(env, argv_,0);
AVFormatContext *pFormatctx=NULL;
if (avformat_open_input(&pFormatctx,name,NULL,NULL)!=0){
return (*env)->NewStringUTF(env,"a");
}
if(pFormatctx==NULL){
return (*env)->NewStringUTF(env,"b");
}
if(avformat_find_stream_info(pFormatctx,NULL)<0){
return (*env)->NewStringUTF(env,"c");
}
av_dump_format(pFormatctx, 0, name, 0);
videostream=-1;
AVCodecContext *pCodecCtxOrig = NULL;
AVCodecContext *pCodecCtx = NULL;
for (i=0;i<pFormatctx->nb_streams;i++){
if((pFormatctx->streams[i]->codecpar->codec_type)==AVMEDIA_TYPE_VIDEO){
videostream=i;
break;
}
}
if(videostream==-1){
return (*env)->NewStringUTF(env,"d");
}
pCodecCtx=pFormatctx->streams[videostream]->codecpar;
AVCodec *pCodec = NULL;
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL){
return (*env)->NewStringUTF(env,"e");
}
pCodecCtx=avcodec_alloc_context3(pCodec);
if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){
return (*env)->NewStringUTF(env,"g");
}
AVFrame *pFrame = NULL,*pFrameRBG=NULL;
pFrame=av_frame_alloc();
pFrameRBG=av_frame_alloc();
if(pFrameRBG==NULL){
return (*env)->NewStringUTF(env,"h");
}
uint8_t *buffer=NULL;
int numBytes;
numBytes=av_image_get_buffer_size(AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height,1);
buffer=(uint8_t *)av_malloc(numBytes* sizeof(uint8_t));
av_image_fill_arrays(pFrameRBG->data,pFrameRBG->linesize,buffer,AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height,1);
struct SwsContext *sws_ctx = NULL;
int frameFinished;
AVPacket *packet=av_packet_alloc();
sws_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGB24,SWS_BILINEAR,NULL,NULL,NULL);
i=0;
while(av_read_frame(pFormatctx,&packet)>=0){
if(packet->stream_index==videostream){
int used=avcodec_send_packet(pCodecCtx,&packet);
used=avcodec_receive_frame(pCodecCtx,pFrame);
if (used < 0 && used != AVERROR(EAGAIN) && used != AVERROR_EOF){
break;
} else{
if (used == AVERROR(EAGAIN) || used == AVERROR_EOF){
break;
}
}
sws_scale(sws_ctx,(uint8_t const * const *)pFrame->data,pFrame->linesize,0,pCodecCtx->height,pFrameRBG->data,pFrameRBG->linesize);
if(++i<=5){
SaveFrame(pFrameRBG,pCodecCtx->width,pCodecCtx->height,i);
}
}
av_packet_free(&packet);
}
char blubuk[50];
sprintf(blubuk,"%d",buffer);
av_free(buffer);
av_frame_free(&pFrameRBG);
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
avcodec_close(pCodecCtxOrig);
avformat_close_input(&pFormatctx);
return (*env)->NewStringUTF(env,blubuk);
}
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame){
FILE *pFile;
char szFilename[32];
int y;
sprintf(szFilename, "frame%d.ppm", iFrame);
pFile=fopen(szFilename,"wb");
if(pFile==NULL){
return;
}
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
for(y=0; y<height; y++){
fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);
}
fclose(pFile);
}
UPDATE:
I am getting "-22" from "int used=avcodec_send_packet(pCodecCtx,packet);".Can't figure out where i went wrong.
Related
So I was trying to display one translucent farbfeld image on top of another, often opaque farbfeld image (named f2.ff and f.ff in order) with the use of XRender to get the alpha compositing but due to the lack of examples on XRender and me being new to Xlib it does not work :)
and the translucent image which should have been displayed on top(f2.ff) is flickering weirdly.
Here is the code :
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize.h"
#include <string.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrender.h>
typedef struct XWindow XWindow;
struct XWindow
{
Display * dpy;
Window root;
Visual * vis;
Colormap cmap;
XWindowAttributes attr;
XSetWindowAttributes swa;
Window win;
int screen;
unsigned int width;
unsigned int height;
Atom wm_delete_window;
};
struct head
{
char ma [7];
unsigned int w;
unsigned int h;
};
unsigned char * ffread(const char * path,unsigned int * w,unsigned int * h)
{
struct head * hh;
size_t filelen;
unsigned char * buffer;
unsigned short temp=0;
size_t i=0;
FILE * file;
file=fopen(path,"rb");
if(file == NULL)
{
puts("cant open the file");
exit(1);
}
hh=malloc(16*sizeof(unsigned short));
fread(hh,2,15,file);
if(strcmp("farbfeld",hh->ma))
{
puts("Invalid file format");
exit(1);
}
*w=ntohl(hh->w);
*h=ntohl(hh->h);
printf("%d %d\n",*w,*h);
filelen=(*w)*(*h)*4;
buffer=malloc(filelen*sizeof(char));
fseek(file,16,SEEK_SET);
for(; i<filelen; i++)
{
fread(&temp,2,1,file);
if(i%4==0||i==0)
{
buffer[i+2]=(ntohs(temp)/257);
}
else if(i%2==0)
{
buffer[i-2]=(ntohs(temp)/257);
}
else
{
buffer[i]=(ntohs(temp)/257);
}
}
fclose(file);
return buffer;
}
int main(void)
{
XWindow xw;
unsigned char * data;
unsigned char * bdata;
unsigned char * im2;
unsigned int wim=0,him=0, w=0,h=0, wim2=0,him2 =0;
XImage * image;
Pixmap pix;
Picture pic;
Picture picdst;
GC gc;
XImage * imagebg;
Pixmap pix2;
Picture pic2bg;
memset(&xw, 0, sizeof xw);
xw.dpy = XOpenDisplay(NULL);
if(!xw.dpy) puts("Could not open a display; perhaps $DISPLAY is not set?");
xw.root = DefaultRootWindow(xw.dpy);
xw.screen = XDefaultScreen(xw.dpy);
xw.vis = XDefaultVisual(xw.dpy, xw.screen);
xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
xw.swa.colormap = xw.cmap;
xw.swa.event_mask =
ExposureMask | KeyPressMask | KeyReleaseMask |
ButtonPress | ButtonReleaseMask| ButtonMotionMask |
Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
PointerMotionMask | KeymapStateMask;
h=DisplayHeight(xw.dpy,xw.screen);
w=DisplayWidth(xw.dpy,xw.screen);
xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, w, h, 0,
XDefaultDepth(xw.dpy, xw.screen), InputOutput,
xw.vis, CWEventMask | CWColormap, &xw.swa);
XStoreName(xw.dpy, xw.win, "X11");
XMapWindow(xw.dpy, xw.win);
xw.wm_delete_window = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(xw.dpy, xw.win, &xw.wm_delete_window, 1);
XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
xw.width = (unsigned int)xw.attr.width;
xw.height = (unsigned int)xw.attr.height;
data=ffread("./f.ff",&wim,&him);
bdata=(unsigned char *)malloc(w*h*4);
stbir_resize_uint8(data,wim,him,0,bdata,w,h,0,4);
im2=ffread("./f2.ff",&wim2,&him2);
picdst=XRenderCreatePicture(xw.dpy,xw.win,XRenderFindStandardFormat(xw.dpy, PictStandardRGB24),0,0);
image=XCreateImage(xw.dpy,CopyFromParent,32,ZPixmap, 0,(char *)im2,wim2, him2,4*8, 4 * wim2);
pix=XCreatePixmap(xw.dpy,xw.win,wim2,him2,32);
gc=XCreateGC(xw.dpy,pix,0,NULL);
XPutImage(xw.dpy,pix,gc,image,0,0,0,0,wim2,him2);
pic=XRenderCreatePicture(xw.dpy,pix,XRenderFindStandardFormat(xw.dpy, PictStandardARGB32),0,0);
imagebg =XCreateImage(xw.dpy,CopyFromParent,32,ZPixmap, 0,(char *)bdata,w, h,4*8, 4 * w);
pix2=XCreatePixmap(xw.dpy,xw.win,w,h,32);
gc=XCreateGC(xw.dpy,pix2,0,NULL);
XPutImage(xw.dpy,pix2,gc,imagebg,0,0,0,0,w,h);
pic2bg=XRenderCreatePicture(xw.dpy,pix2,XRenderFindStandardFormat(xw.dpy, PictStandardARGB32),0,0);
while(1)
{
pic2bg=XRenderCreatePicture(xw.dpy,pix2,XRenderFindStandardFormat(xw.dpy, PictStandardARGB32),0,0);
picdst=XRenderCreatePicture(xw.dpy,xw.win,XRenderFindStandardFormat(xw.dpy, PictStandardRGB24),0,0);
pic=XRenderCreatePicture(xw.dpy,pix,XRenderFindStandardFormat(xw.dpy, PictStandardARGB32),0,0);
XRenderComposite(xw.dpy,PictOpSrc,pic,None,picdst,0,0,0,0,0,0,wim2,him2);
XRenderComposite(xw.dpy,PictOpSrc,pic2bg,None,picdst,0,0,0,0,0,0,w,h);
XRenderFreePicture(xw.dpy,picdst);
XRenderFreePicture(xw.dpy,pic2bg);
XRenderFreePicture(xw.dpy,pic);
}
}
Okay so I have all this code for a sudoku solver (it's not done, I still need my find next function and legal move function) but I could use some help with printing. The code asks for the user to upload a file to read, and then prints out the puzzle. This means sudoku can be 3x3 or 4x4, all the way up to 25x25. What I need help with, is in my print_puzzle function, how do I make sure that it prints out in blocks? Like if it was 3x3, there would be 9 3x3 boxes for the puzzle, etc. Hopefully that makes sense, anyways here's the code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
bool prompt_for_file (void);
bool load_puzzle(char filename[]);
void print_puzzle (void);
bool solve_puzzle(void);
bool find_next( int *row, int *col, int dir);
bool legal_move(int num; int row; int col);
#define MAX_SIZE 25
#define FORWARD 1
#define BACKWARD 0
int puzzle[MAX_SIZE][MAX_SIZE];
int puzzle_size;
int block_size;
int main(void)
{
if (!prompt_for_file())
{return -1;}
print_puzzle();
if (solve_puzzle())
{print_puzzle();}
else
{return -1;}
return 0;
}
bool solve_puzzle(void)
{
int dir;
int R;
int C;
int n;
int previous_n;
dir = FORWARD;
while(find_next(&R, &C, dir))
{
dir= BACKWARD;
previous_n=abs(puzzle[R][C]);
puzzle[R][C]= 0;
for (n=previous_n+1; n<=puzzle_size; n++)
{
if (legal_move(n, R, C))
{
puzzle[R][C] = -n;
dir = FORWARD;
break;
}
}
}
if (dir== FORWARD)
{return true;}
else
{return false;}
}
void print_puzzle (void)
{
int r;
int c;
printf("\n");
for (r=0;r<puzzle_size;r++)
{
for (c=0;c<puzzle_size;c++)
{
printf("%3d", abs(puzzle[r][c]));
//put something in to define blocks
}
printf("\n");
}
printf("\n");
}
/*
bool find_next( int *row, int *col, int dir)
{
*R=r;
*C=c;
}
*/
bool prompt_for_file (void)
{
char filename[100];
do
{
printf("Enter a file name (or ""quit""): ");
scanf("%s",&filename[0]);
if ( strcmp(filename,"quit")==0 )
{
filename[0]='\0';
printf("quitting\n");
return false;
}
} while( load_puzzle(filename)!=true );
return true;
}
bool load_puzzle(char filename[])
{
int r;
int c;
int dummy;
FILE *fileptr;
// open the file but return if not successful
fileptr = fopen(filename,"r");
if ( fileptr==NULL)
{
printf("the file was not opened: %s\n", filename);
return false;
}
else
{
printf("the file was opened: %s\n", filename);
}
// read the sizing info
fscanf(fileptr,"%d",&puzzle_size);
printf("the number of rows and cols: %d\n",puzzle_size);
if (puzzle_size>MAX_SIZE)
{
printf("puzzle is too big %d. Max size is %d\n", puzzle_size,MAX_SIZE);
return false;
}
block_size=sqrt(puzzle_size);
// read the data
for (r=0;r<puzzle_size;r++)
{
for (c=0;c<puzzle_size;c++)
{
if ( fscanf(fileptr,"%d",&puzzle[r][c])!=1 )
{
printf("insufficient number of elements\n");
return false;
}
}
}
// check to see if all of the data was read
// and that the end of the input file has been reached
if (fscanf(fileptr,"%d",&dummy) ==1)
{
printf("WARNING: not all numbers from file were used.\n");
}
if (feof(fileptr))
{
printf("The end of the input file has been reached.\n");
}
fclose(fileptr);
return true;
}
Thank you!!:)
i have a http client written in c , and in some section i get the time and fill in in buffer , i checked all the input values are valid , but when the function runs it gives segmentation fault , Line number 77 , the line :
strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&now));
i tested the inputs by debugger and non of them is problematic
After compiling run with this command
./COMPILED_FILE_NAME https://stackoverflow.com/ -d 1:1:1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/types.h>
#define HEADER "-h"
#define TIME_STAMP "-d"
#define PROTOCOL "http://"
#define RFC1123FMT "%a, %d %b %Y %H:%M:%S GMT"
#define DEFAULT_PORT 80
#define BUFFER_SIZE 256
typedef struct sockaddr_in sockaddr_t;
void printError(int flag,char * name);
int parseUrl(char * url,char** host,int * portt ,char ** path);
int checkString(const char * date);
int parseDate(char* date,int * day,int * hour,int* minute);
void freeData();
int socketConnect(char * host,int port,char * page,char* requestType , char * dateRequest );
char * host; // the url with out any addititons
char * path; // the path after the url
int main(int argc,char * argv[])
{
time_t now;
now = time(NULL);
char timebuf[BUFFER_SIZE/2];
int headrFlag=0;
int timeFlag=0;
int day=0,hour=0,minute=0;
// char * host;//=(char*)malloc(sizeof(char)*128);
// char * path;//=(char*)malloc(sizeof(char)*128);
char requestType[BUFFER_SIZE];
char dateRequest[BUFFER_SIZE];
bzero(dateRequest,sizeof(dateRequest));
strcpy(requestType,"GET");
int port=DEFAULT_PORT;
if(argc >1 && argc <=5) // the host at least their
{
// checking the incoming args
int i = 1;
for(;i<argc;i++)
{
if(strcmp(argv[i],HEADER)==0)
{
if(headrFlag==0)
{
headrFlag=1;
strcpy(requestType,"HEAD");
}
else
{
printError(0,"");
break;
}
}
else if(strcmp(argv[i],TIME_STAMP)==0)
{
// take the date from the next i , if not there as error
if(timeFlag==0)
{
timeFlag=1;
if(i+1!=argc && parseDate(argv[i+1],&day,&hour,&minute)!=-1) // there is date "thing" after the flag
{
now=now-(day*24*3600+hour*3600+minute*60); //where day, hour and min are the values
//from the input
strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&now));
//timebuf holds the correct format of the time
sprintf(dateRequest,"If-Modified-Since: %s\n",timebuf);
i++;
continue;
}
else
{
printError(1,"");
}
}
else
{
printError(0,"");
}
printError(0,"");
break;
}
else // the host
{
if(parseUrl(argv[i],&host,&port,&path)<0)
{
printError(1,"");
}
}
}
// connect after every thing is valid
if(host!=NULL){socketConnect(host,port,path,requestType,dateRequest);}else{printError(0,"");}
}
else
{
printError(1,"");
}
return 0;
}
void printError(int flag,char * name)
{
// 0 wrong command usage
//1 wrong input
//2 system call failure
if(flag==0)
{
printf("Usage: client [-h] [-d <time-interval>] <URL>\n");
}
else if(flag==1) // wrong input
{
printf("wring input\n");
}
else // flag ==2 , sys calls
{
perror(name);
}
freeData();
exit(-1);
}
// handles the validation of the url
int parseUrl(char * url,char** host,int * portt ,char ** path)
{
char * det=":";
char * det1="/";
char * port;
char * temp;
char * pathValue;
int pathSize=0,hostSize=0;
int addSize=0;
int portNumber=80;
char * urlToParse;
if((temp=strstr(url,PROTOCOL))!=NULL && temp==url) // checking http://
{
temp=&temp[strlen(PROTOCOL)];
urlToParse=temp;
if(strlen(urlToParse) <=1)
return -1;
}
else
{
return -1;
}
if((temp=strstr(temp,det))!=NULL) // checking port
{
int len1 = strlen(temp)-1; // length from the : to the end
addSize=len1;
char * temp1;
if((temp1=strstr(temp,det1))!=NULL)
{
pathSize= strlen(temp1);
pathValue=temp1;
int portLength= len1-pathSize;
port = (char*)malloc(sizeof(char)*portLength+1);
if(port==NULL)
{
printError(2,"malloc");
}
port[portLength]='\0';
strncpy(port,++temp,portLength);
if(checkString(port)<0)
return -1;
portNumber=atoi(port);
free(port);
addSize=len1+1;
}
}
else // no port
{
temp=urlToParse;
if((temp=strstr(temp,det1))==NULL) // checking filepath
{
return -1;
}
else
{
pathValue=temp;
pathSize=strlen(temp);
addSize=pathSize;
}
}
hostSize=strlen(urlToParse)-addSize;
*host =(char*)malloc(sizeof(char)*(hostSize+1));
if(*host==NULL)
{
printError(2,"malloc");
}
**host=NULL;
* path =(char*)malloc(sizeof(char)*(pathSize+1));
if(*path==NULL)
{
printError(2,"malloc");
}
**path=NULL;
// *path=pathValue;
strcpy(*path,pathValue);
*portt=portNumber;
strncpy(*host,urlToParse,hostSize);
return 0;
}
// checks if the number is valid
int checkString(const char * date)
{
if(date==NULL || strcmp(date,"")==0)
{
return -1;
}
int len = strlen(date);
if(strlen(date)>1 && strncmp(&date[0],"-",1)==0 )
{
date++;
}
while(date && strcmp(date,"")!=0)
{
if(isdigit(*(date++))==0)
{
return -1;
}
}
return 1;
}
// converts from chars to int
int parseDate(char* date,int * day,int * hour,int* minute)
{
char * det=":";
// int days,hours,minutes;
char * dayss = strtok(date,det);
char * hourss = strtok(NULL,det);
char * moinutss = strtok(NULL,det);
if(dayss ==NULL || hourss==NULL||moinutss==NULL)
{
return -1;
}
if(checkString(dayss)<0 || checkString(hourss)<0 || checkString(moinutss)<0 )
return -1;
*day = atoi(dayss);
*hour= atoi(hourss);
*minute=atoi(moinutss);
return 1;
}
// free what ever memory we used
void freeData()
{
if(host !=NULL)
{
free(host);
}
if(path!=NULL)
{
free(path);
}
}
// handles the connection to the server
int socketConnect(char * host,int port,char * page,char* requestType , char * dateRequest )
{
struct in_addr serverIp;
struct hostent * hostt =NULL;
hostt= (struct hostent *)gethostbyname(host);
if(hostt==NULL)
{
freeData();
herror("");
printf("\n");
exit(0);
}
struct addr_in** addresses = (struct in_addr **)hostt->h_addr_list;
int i=0;
// char * ss= inet_ntoa(((struct in_addr*)hostt->h_addr)->s_addr);
// serverIp.s_addr=inet_addr(ss);
struct sockaddr_in packet;
packet.sin_family=AF_INET;
packet.sin_port=htons(port);
packet.sin_addr.s_addr=((struct in_addr*) hostt->h_addr)->s_addr;
int socketFd ;
if((socketFd=socket(PF_INET,SOCK_STREAM,0))<0)
{
printError(2,"socket");
}
if(connect(socketFd,(struct sockaddr*)&packet,sizeof(packet))<0)
{
printError(2,"connect");
}
char buffer[BUFFER_SIZE*4];
char * req = malloc(sizeof(requestType)+sizeof(page)+sizeof(dateRequest)+BUFFER_SIZE);
if(req==NULL)
{
freeData(2,"malloc");
}
sprintf(req,"%s http://%s%s HTTP/1.0\r\n%s\n",requestType,host,page,dateRequest);
printf("HTTP request =\n%s\nLEN = %d\n",req,strlen(req));
send(socketFd,req,strlen(req),0);
int sizeOfResponse=0;
int reading=0 ;
do
{
bzero(buffer,sizeof(buffer));
reading= read(socketFd,buffer,sizeof(buffer),0);
if(reading >0)
{
printf("%s",buffer);
sizeOfResponse=sizeOfResponse+strlen(buffer);
}
}
while(reading>0);
printf("\nTotal received response bytes: %d\n",sizeOfResponse);
close(socketFd);
free(req);
freeData();
}
Root cause: you must #include <time.h>.
The reason is that without a declaration in scope the compiler assumes that gmtime() returns int. In reality it returns struct tm *, and apparently on your platform a pointer is wider than the integer.
You should enable all warnings and pay attention to them.
Is there any way to include http://freeimage.sourceforge.net/index.html in my c test program without first installing the library? It fails to compile because of some memset..
Here is my C code. Is there any way to make it work? Please try compiling it and tell me how to do it if it works?
#define NAZIV_DATOTEKE 50
#include <stdio.h>
#include "FreeImage.h"
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message);
FIBITMAP* GenericLoader(const char* lpszPathName, int flag);
int main(){
FreeImage_Initialise();
FIBITMAP *dib, *ptr;
char ulaz_slika[NAZIV_DATOTEKE] = "bmp_24.bmp";
char izlaz_slika[NAZIV_DATOTEKE] = "free.bmp"; //podrazumevana vrednost
dib = GenericLoader(ulaz_slika, 0);
//slika = FreeImage_Load(FIF_BMP, "bmp_24.bmp", BMP_DEFAULT);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
if (dib) {
printf("Ucitan \"%s\".\n", ulaz_slika);
}
FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(ulaz_slika, 0);
if ((fif != FIF_BMP) && (fif != FIF_ICO) && (fif != FIF_JPEG) && (fif != FIF_PNG) && (fif != FIF_TIFF)){
printf("Format slike nije podrzan.\n");
return 1;
}
ptr = FreeImage_ConvertTo24Bits(dib);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
FreeImage_Unload(dib);
FreeImage_SetOutputMessage(FreeImageErrorHandler);
dib = ptr;
if (dib) {
printf("Konvertovan u RGB.\n");
}
const char *slika = (const char*)FreeImage_GetBits(dib);
if (FreeImage_Save(fif, dib, izlaz_slika, BMP_DEFAULT)) {
printf("Snimljen \"%s\".\n", izlaz_slika);
}
if (dib) {
FreeImage_Unload(dib);
}
FreeImage_DeInitialise();
return 0;
}
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message){
printf("\n*** ");
if(fif != FIF_UNKNOWN) {
if (FreeImage_GetFormatFromFIF(fif))
printf("%s Format\n", FreeImage_GetFormatFromFIF(fif));
}
printf(message);
printf(" ***\n");
}
FIBITMAP* GenericLoader(const char* lpszPathName, int flag) {
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
// check the file signature and deduce its format
// (the second argument is currently not used by FreeImage)
fif = FreeImage_GetFileType(lpszPathName, 0);
if(fif == FIF_UNKNOWN) {
// no signature ?
// try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(lpszPathName);
}
// check that the plugin has reading capabilities ...
if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
// ok, let's load the file
FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag);
// unless a bad file format, we are done !
return dib;
}
return NULL;
}
No you cannot. To compile your source, the linker needs the library.
I'm writing a little program in C, for check the HTML file have the right open and close tags?
but i've got some issues...
i have a file what contains the all possible tags, named tags.txt(those are only the first ones):
<a>
</a>
<abbr>
</abbr>
<area>
</area>
<aside>
</aside>
and i have the htmlfile.html, what I have to check:
<!--#echo var="date" -->
<area>
</area>
<area>
</area>
secondly, i want to replace the comments like this to the sysdate
like , the format is OK i can do it, but the prog puts in the file
this
my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX_SIZE 512
void menu();
void check();
void datumos();
int main(int argc,char *argv[])
{
menu();
return 0;
}
void menu()
{
char menu[MAX_SIZE];
while(1 < 2)
{
printf("\npress a button:\n\n");
printf("\tFile HTML check..............:c\n");
printf("\t<!--#echo var="date" -->...........:d\n");
printf("\tExit:\tCTRL + C\n");
scanf("%s",menu);
if( strcmp(menu,"c") == 0 )
{
check();
}
else if( strcmp(menu,"d") == 0 )
{
datumos();
}
}
}
void check()
{
FILE *htmlfile;
FILE *checkfile;
htmlfile = fopen("htmlfile.html","w");
checkfile = fopen("tags.txt","r");
char line[MAX_SIZE];
char htmlline[MAX_SIZE];
char tags[189][30];
int i=0;
printf("\tcheck__1\n");
while(fgets(line,sizeof(line),checkfile) != NULL)
{
int j;
for(j=0; j<sizeof(line); ++j)
{
tags[i][j]=line[j];
}
++i;
}
printf("\tcheck__2\n");
int k=0; char htmlfiletags[MAX_SIZE][30];
while(fgets(htmlline,sizeof(htmlline),htmlfile) != NULL)
{
char currentline[sizeof(htmlline)];
int j=0;
if( currentline[j]=="<" )
{
while(currentline[j]!=">")
{
htmlfiletags[k][j]=currentline[j];
++j;
}
strcat(htmlfiletags[k][j+1],">");
++k;
}
}
printf("\tcheck__3\n");
int n;
for(n=0; n<sizeof(htmlfiletags); ++n)
{
int j; int howmanytimesnot=0;
for(j=0; j<sizeof(tags); ++j)
{
printf("\tcheck__3/1\n");
if(strcmp(htmlfiletags[n],tags[j])==0)
{
printf("\t%d\n", howmanytimesnot);
++howmanytimesnot;
}
}
printf("\tcheck__3/3\n");
if(!(howmanytimesnot<sizeof(tags)))
{
printf("\tcheck__3/4\n");
printf("the file is not wellformed");
exit (1);
}
}
printf("\tcheck__4\n");
}
void copy_file(const char *from,const char *to)
{
FILE *fr;
FILE *t;
fr = fopen(from,"r");
t = fopen(to,"w");
char line[MAX_SIZE];
char row[MAX_SIZE];
while(fgets(line,sizeof(line),fr) != NULL)
{
sscanf(line,"%s",row);
fprintf(t,"%s\n",row);
}
fclose(fr);
fclose(t);
remove("tempfile.html");
}
void datumos()
{
time_t now = time(NULL);
struct tm *t = localtime(&now);
char date_time[30];
strftime( date_time, sizeof(date_time), "%x_%X", t );
FILE *htmlfile;
FILE *tempfile;
htmlfile = fopen("htmlfile.html","r");
tempfile = fopen("tempfile.html","w");
char line[MAX_SIZE];
//char datecomment[]="<!--#echo var=date -->";
while(fgets(line,sizeof(line),htmlfile) != NULL)
{
if( strcmp(line,"<!--#echo var="date" -->") == 0 )
{
char row[40];
strcpy(row,"<!--");
strcat(row, date_time);
strcat(row,"-->");
printf("%s",row);
fputs(row,tempfile);
}
else
{
fputs(line,tempfile);
}
}
fclose(htmlfile);
fclose(tempfile);
copy_file("tempfile.html","htmlfile.html");
}
it dies in this, in the inner for loop, in the if at the 200th check... i dont know why...
int n;
for(n=0; n<sizeof(htmlfiletags); ++n)
{
int j; int howmanytimesnot=0;
for(j=0; j<sizeof(tags); ++j)
{
printf("\tcheck__3/1\n");
if(strcmp(htmlfiletags[n],tags[j])==0)
{
printf("\t%d\n", howmanytimesnot);
++howmanytimesnot;
}
}
printf("\tcheck__3/3\n");
if(!(howmanytimesnot<sizeof(tags)))
{
printf("\tcheck__3/4\n");
printf("the file is not wellformed");
exit (1);
}
}
Thanks for all reply!!
G
Your code is very complicated, it has several issues.
Here's one:
for(j=0; j<sizeof(tags); ++j)
this will not do what I believe you expect; sizeof(tags) is not the array length of tags (which is declared as char tags[189][30];), it's the total size of the variable. So, this loop will go from 0 to 189 * 30 - 1, i.e. 5669, and thus index way out beyond the end of array.
Also, the idea to use sizeof here in any way is wrong, since the content of tags comes from a file and it thus impossible for the compiler to know. Remember that sizeof is evaluated at compile-time, for expressions like these.
You need to have a variable (e.g. size_t num_tags) that you increment for each line parsed from the tags file, and that you later use to iterate over tags.
Do not use regex, or some kind of string parsing, to parse HTML. Instead search the web, or this site, for a c library to parse html. Then check the parsed HTML file for the tags. This will ease the development a lot as you don't have to parse the files yourself.
i've fixed some things, but
- i still cant check the file's htmltags, dies at the same loop, i've fixed allocation of the tags array
- when in the htmlfile are 2 or more different comments and i'm replacing the comment the program replaces it with the sysdate, but the program copy the another comments badly, like =>
the code is now:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX_SIZE 512
void menu();
void check();
void datumos();
int main(int argc,char *argv[])
{
menu();
return 0;
}
void menu()
{
char menu[MAX_SIZE];
while(1 < 2)
{
printf("\npress a button:\n\n");
printf("\tFile HTML check..............:c\n");
printf("\t<!--#echo var="date" -->...........:d\n");
printf("\tExit:\tCTRL + C\n");
scanf("%s",menu);
if( strcmp(menu,"c") == 0 )
{
check();
}
else if( strcmp(menu,"d") == 0 )
{
datumos();
}
}
}
void check()
{
FILE *htmlfile;
FILE *checkfile;
htmlfile = fopen("htmlfile.html","r");
checkfile = fopen("tags.txt","r");
char line[MAX_SIZE];
char htmlline[MAX_SIZE];
int i2=0;
printf("\tcheck__1\n");
while(fgets(line,sizeof(line),checkfile) != NULL)
{
++i2;
}
char tags[i2][20];
int i=0;
printf("\tcheck__11\n");
while(fgets(line,sizeof(line),checkfile) != NULL)
{
int j;
for(j=0; j<sizeof(line); ++j)
{
tags[i][j]=line[j];
}
++i;
}
printf("\tcheck__2\n");
int k=0; char htmlfiletags[MAX_SIZE][30];
while(fgets(htmlline,sizeof(htmlline),htmlfile) != NULL)
{
char currentline[sizeof(htmlline)];
int j=0;
if( currentline[j]=="<" )
{
while(currentline[j]!=">")
{
htmlfiletags[k][j]=currentline[j];
++j;
}
strcat(htmlfiletags[k][j+1],">");
++k;
}
}
printf("\tcheck__3\n");
int n;
for(n=0; n<sizeof(htmlfiletags); ++n)
{
int j; int howmanytimesnot=0;
for(j=0; j<sizeof(tags); ++j)
{
//printf("\tcheck__3/1\n");
if(strcmp(htmlfiletags[n],tags[j])==0)
{
// printf("\t%d\n", howmanytimesnot);
++howmanytimesnot;
}
}
printf("\tcheck__3/3\n");
if(!(howmanytimesnot<sizeof(tags)))
{
printf("\tcheck__3/4\n");
printf("the file is not wellformed");
exit (1);
}
}
printf("\tcheck__4\n");
}
void copy_file(const char *from,const char *to)
{
FILE *fr;
FILE *t;
fr = fopen(from,"r");
t = fopen(to,"w");
char line[MAX_SIZE];
char row[MAX_SIZE];
while(fgets(line,sizeof(line),fr) != NULL)
{
sscanf(line,"%s",row);
fprintf(t,"%s\n",row);
}
fclose(fr);
fclose(t);
remove("tempfile.html");
}
void datumos()
{
time_t now = time(NULL);
struct tm *t = localtime(&now);
char date_time[30];
strftime( date_time, sizeof(date_time), "%x_%X", t );
FILE *htmlfile;
FILE *tempfile;
htmlfile = fopen("htmlfile.html","r");
tempfile = fopen("tempfile.html","w");
char line[MAX_SIZE];
char* datecomment="<!--#echo var=\"date\" -->";
while(fgets(line,sizeof(line),htmlfile) != NULL)
{
int i3; int db=0;
for(i3=0; i3<strlen(datecomment); ++i3)
{
if(line[i3]==datecomment[i3])
{
++db;
}
}
if(db==strlen(datecomment))
{
char row[30];
strcpy(row,"<!--");
strcat(row, date_time);
strcat(row,"-->\n");
fputs(row,tempfile);
}
else
{
fputs(line,tempfile);
}
}
fclose(htmlfile);
fclose(tempfile);
copy_file("tempfile.html","htmlfile.html");
}
the currentline it's not necessary,and i've fixed the compares too
while(fgets(htmlline,sizeof(htmlline),htmlfile) != NULL)
{
int j=0;
if( htmlline[j]=='<' )
{
while(htmlline[j]!='>')
{
htmlfiletags[k][j]=htmlline[j];
++j;
}
strcat(htmlfiletags[k][j+1],">");
++k;
}
}
-in addition, the another problem to replace only the suitable comments, and dont hurt the different ones still dont work
"so it replaces
<!--#echo var="date" --> to the sysdate, it's ok, but when there are different comments like
<!--#include something -->, it wont be copied back well, in the htmlfile will be only <!--#include"
ideas?