Module on C for Python on Windows Code blocks - c

I'm trying to create the module on C for python, but I got some troubles with it:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
FILE *fp = fopen("write.txt", "w");
fputs("Real Python!", fp);
fclose(fp);
return 1;
}
static PyObject *method_fputs(PyObject *self, PyObject *args) {
char *str, *filename = NULL;
int bytes_copied = -1;
/* Parse arguments */
if(!PyArg_ParseTuple(args, "ss", &str, &filename))
return NULL;
FILE *fp = fopen(filename, "w");
bytes_copied = fputs(str, fp);
fclose(fp);
return PyLong_FromLong(bytes_copied);
}
static PyMethodDef FputsMethods[] = {
{"fputs", method_fputs, METH_VARARGS, "Python interface for fputs C library function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef fputsmodule = {
PyModuleDef_HEAD_INIT,
"fputs",
"Python interface for the fputs C library function",
-1,
FputsMethods
};
I use this code, and I got such mistakes when I try to build it
undefined reference to `__imp__PyArg_ParseTuple_SizeT'
undefined reference to `__imp_PyLong_FromLong'
error: ld returned 1 exit status
What's wrong with it?

Related

How to convert image file *.jpg to hex code in C?

I'm trying to read a JPG image file and convert it to string of hex code (not hex of pixel) in C.
Something like:
FFD8FFE000114A464946000102030405060708090AFFDB00....
I tried many way but not working. Someone has any idea?
My code which I tried with stb libraries: https://codeload.github.com/nothings/stb/zip/master
// USAGE: gcc -std=c99 image.c -o image -lm
#include <stdio.h>
#include <math.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
const size_t NUM_PIXELS_TO_PRINT = 10U;
int main(void) {
int width, height, comp;
unsigned char *data = stbi_load("r3.jpg", &width, &height, &comp, 0);
if (data) {
printf("width = %d, height = %d, comp = %d (channels)\n", width, height, comp);
for (size_t i = 0; i < NUM_PIXELS_TO_PRINT * comp; i++) {
printf("%02x%s", data[i], ((i + 1) % comp) ? "" : "\n");
}
printf("\n");
}
return 0;
}
The error I got when try with John Smith:
ImageProcess.c: In function ‘main’:
ImageProcess.c:14:5: warning: implicit declaration of function ‘bzero’ [-Wimplicit-function-declaration]
bzero(data, fsize + 1);
^
ImageProcess.c:18:5: warning: implicit declaration of function ‘hexlifyn’ [-Wimplicit-function-declaration]
char* yourDataStr = hexlifyn((char*)data, (uint)fsize);
^
ImageProcess.c:18:48: error: ‘uint’ undeclared (first use in this function)
char* yourDataStr = hexlifyn((char*)data, (uint)fsize);
^
ImageProcess.c:18:48: note: each undeclared identifier is reported only once for each function it appears in
ImageProcess.c:18:53: error: expected ‘)’ before ‘fsize’
char* yourDataStr = hexlifyn((char*)data, (uint)fsize);
^
ImageProcess.c: At top level:
ImageProcess.c:21:28: error: unknown type name ‘uint’
char *hexlifyn(char *bstr, uint str_len) {
^
If your goal is to get the contents of a file as hex string than that should work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char* file_name = "/path/to/any.png";
FILE *f = fopen(file_name, "rb");
if (f==NULL) return;
fseek(f, 0, SEEK_END);
size_t fsize = ftell(f);
fseek(f, 0, SEEK_SET);
void*data = malloc(fsize + 1);
bzero(data, fsize + 1);
fread(data, 1, fsize, f);
fclose(f);
char* yourDataStr = hexlifyn((char*)data, (uint)fsize);
}
char *hexlifyn(char *bstr, uint str_len) {
char *hstr=malloc((str_len*2)+1);
bzero(hstr,(str_len*2)+1);
char *phstr=hstr;
for(int i=0; i<str_len;i++) {
*phstr++ =v2a((bstr[i]>>4)&0x0F);
*phstr++ =v2a((bstr[i])&0x0F);
}
*phstr++ ='\0';
return hstr;
}
char v2a(int c) {
const char hex[] = "0123456789abcdef";
return hex[c];
}
From your comment I understand that you want to retrieve the binary contents of a file (i.e. a JPG image) as a hexadecimal string.
What you're looking for is something called "hex dump". There are various libraries and snippets available that allow doing this with C.
This stackoverflow question addresses exactly this issue.
This will give you image file output as a continuous hex string in your terminal as well as a .txt file:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
string myText;
int main()
{
system("xxd -p image.jpg > image.txt | tr -d '\n'");
ifstream MyReadFile("./image.txt");
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
MyReadFile.close();
return 0;
}

Create/Change/Use an extern Variable in C

I have a header file containing:
extern char *finalLoggerPath;
I am trying to implement a function that can initialize or modify the finalLoggerPath variable.
My main function indirectly calls a function defined in a second file. This second function generates a path which does not yet exist, and saves it in two file-scope variables, finalPath and finalLoggerPath. After that is done, I would like another function defined in a third file to be able to print the finalLoggerPath.
I have attempted to implement this, but I get an error:
Memory access error (memory dump used)
How can I fix my program?
My code:
// First File
void initLog() {
generateFileNameWithDate();
}
int main(void) {
initLog();
}
// Second File
#define PATHTEST "../TestLogSystem/"
#include "Info.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
char pathToFile[100] = "../TestLogSystem/";
char *actual;
char *finalPath;
char *finalLoggerPath;
int generateFileNameWithDate() {
int counter = 1;
char filename[999];
char filenameBuffer[999];
int notCreatetFile = 1;
char counterS[999];
time_t now = time(NULL);
if (now == -1) {
puts("The time() function failed");
return 1;
}
struct tm *ptm = localtime(&now);
if (ptm == NULL) {
puts("The localtime() function failed");
return 1;
}
strftime(filename, sizeof(filename),
strcat(strcat(pathToFile, "%Y%m%d"), ".json"), ptm);
while (notCreatetFile) {
if (access(filename, F_OK) != -1) {
// file exists
memset(filename, 0, sizeof(filename));
memset(pathToFile, 0, sizeof(pathToFile));
sprintf(pathToFile, "%s", PATHTEST);
memset(filenameBuffer, 0, sizeof(filenameBuffer));
sprintf(counterS, "%d", counter);
strftime(filename, sizeof(filename),
strcat(
strcat(
strcat(
strcat(strcat(pathToFile, filenameBuffer),
"%Y%m%d"), "-Test-"),
counterS), ".json"), ptm);
} else {
// file doesn't exist
finalPath = malloc(strlen(filename) + 1);
printf("finalPath: %s \n", finalPath);
strcpy(finalPath, filename);
strcpy(finalLoggerPath, finalPath);
fopen(finalPath, "w");
notCreatetFile = 0;
}
++counter;
}
return 0;
}
// Third File
#include "Info.h"
void print() {
printf("FinalLoggerPath: %s", finalLoggerPath);
}
I compile it:
gcc CallFileExists.c FileExists.c GetVariableFromFileExists.c

How to implement google mock to mock the C fopen function

I am writing a unit test for embedded C codes using google test/mock. The C function code looks like this.
int readGPIOSysfs(int ioport){
...
FILE *f = fopen("/sys/class/gpio/export", "w");
..
fclose(f);
}
How can I implement a google mock on fopen function call?
Thank you in advance.
I do it using CppuTest instead of Gtest :
//io.c -> imlementation
#include "drivers/io.h"
#include <string.h>
#include <stdio.h>
bool read_io()
{
FILE *fp_driver = fopen("/dev/io/my_device", "rw");
char msg[255] = {0};
if (fp_driver == NULL)
return false;
fread(msg, sizeof(char), 255, fp_driver);
if (strcmp(msg, "This is a test"))
return false;
return true;
}
//io.cpp -> Tests functions
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <stdio.h>
#include <string.h>
extern "C"
{
#include "drivers/io.h"
}
TEST_GROUP(IO)
{
void setup() {
}
void teardown() {
mock().clear();
}
};
// Mocking function
FILE *fopen (const char *__restrict __filename, const char *__restrict __modes)
{
void * r = mock().actualCall(__func__).returnPointerValue();
return (FILE *)r;
}
TEST(IO, simpleTest)
{
/* Create a temp file with a test string inside to match with
implementation function expectation */
FILE * tmp_log_file = tmpfile();
char str[] = "This is a test";
fwrite(str, sizeof(char), strlen(str), tmp_log_file);
rewind(tmp_log_file);
/* Return or temp file pointer for the next call of fopen */
mock().expectOneCall("fopen").andReturnValue(tmp_log_file);
bool r = read_io();
CHECK_TRUE(r);
mock().checkExpectations();
}
int main(int ac, char** av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}

Want to create a file with write mode in C

I am new in C. I want to create a file in linux C program and write environment variables in it. If file already exist I want to open and append. I have written the following code.
char *envFile=getenv("FILENAME");
int fdEnv=-1;
fdEnv=open(envFile,O_CREAT,O_RDWR,O_APPEND);
printf("%d",fdEnv);
char** env;
if(fdEnv>0)
{
for (env = environ; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s",thisEnv);
write(fdEnv,thisEnv,strlen(thisEnv));
}
close(fdEnv);
}
But when I run it first time. A blank file is created. And it stays locked after execution. Looks like some error. Second time it fdEnv stays less than 0.
I really don't understand what is happening here. Please help.
Try using | to separate the flags.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
extern char **environ;
int main(void)
{
char *envFile = getenv("FILENAME");
int fdEnv = -1;
fdEnv = open(envFile, O_CREAT|O_RDWR|O_APPEND, 0644);
printf("%d\n", fdEnv);
int i = 0;
while (environ[i]) {
printf("%s\n", environ[i]);
write(fdEnv, environ[i], strlen(environ[i]));
char lf = '\n';
write(fdEnv, &lf, 1);
i++;
}
close(fdEnv);
return 0;
}
I've run above code on my linux computer and it works.
extern char **environ;
int main()
{
char **env;
char* filename = getenv("FILENAME")
const char* mode = "a";
FILE* file = fopen( filename, mode );
for ( env = environ; *env; ++env )
fprintf( file, "%s\n", *env );
fclose(file);
return(0);
}
You should think about handling when getenv fails, is blank, etc; let me know if you have any questions.

Thread error while compiling the Xml parser in C?

[root#localhost mxml-2.7]# gcc -o xml XmlParser1.c -lmxml
XmlParser1.c: In function ‘main’:
XmlParser1.c:63: warning: assignment discards qualifiers from pointer target type
/usr/local/lib/libmxml.so: undefined reference to `pthread_key_create'
/usr/local/lib/libmxml.so: undefined reference to `pthread_once'
/usr/local/lib/libmxml.so: undefined reference to `pthread_getspecific'
/usr/local/lib/libmxml.so: undefined reference to `pthread_key_delete'
/usr/local/lib/libmxml.so: undefined reference to `pthread_setspecific'
collect2: ld returned 1 exit status
Following error occurred while compiling the XmlParser1.c.
XmlParser1.c:
#include <stdio.h>
#include "mxml.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAX_SIZE 25
static mxml_node_t *xml;
static mxml_node_t *str;
static mxml_node_t *DataSet;
static mxml_node_t *Table;
static mxml_node_t *IsAuthenticated;
static mxml_node_t *AuthenticationDate;
static mxml_node_t *Response;
int main()
{
int fd = 0;
char *Result=NULL;
const char *NewResult=NULL;
mxml_node_t *tree;
mxml_node_t *data;
const char *type = NULL;
FILE *fp = fopen("/home/suneet/mxml-2.7/Sample/main.xml", "r") ;
if (fp == NULL)
{
fclose(fp);
}
else
{
fseek (fp , 0, SEEK_END);
long settings_size = ftell (fp);
rewind (fp);
if (settings_size > 0)
{
tree = mxmlLoadFile(NULL, fp, MXML_NO_CALLBACK);
fclose(fp);
printf("step 1\n");
data = mxmlFindElement(Table, tree, "diffgr:id", NULL, NULL, MXML_DESCEND);
Result = mxmlElementGetAttr(data,"diffgr:id");
printf("diffgr:id:%s\n",(Result == NULL)?"NULL":Result);
mxmlDelete(data);
mxmlDelete(tree);
}
}
return 0;
}
while i am trying to go with the steps given in http://minixml.org/; parse accordingly the xml file there is certain error "undefined error to threads for dynamic library libxml.so.".
Please guide me so that i can successfully parse the xml file.
You need to link with the pthread library using the -pthread option.
gcc -o xml XmlParser1.c -lmxml -pthread
You need to include pthread in you code.
add this line at the beginning of your file
#include<pthread.h>

Resources