c# interview questions
Top c# frequently asked interview questions
I am trying to interface Official C driver
with mongoLab
but getting error that failed to authenticate credentials
. Do anyone have any simple example on how to interface mongolab
using C driver
. This is my example code
const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";
uri = mongoc_uri_new(String_uri);
client = mongoc_client_new_from_uri (uri);
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);
count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
if (count < 0) {
fprintf (stderr, "%s\n", error.message);
} else {
printf ("%" PRId64 "\n", count);
}
Source: (StackOverflow)
I'm using a Python script in conjunction with a thermocouple and a thermocouple reader. To communicate with the thermocouple reader, which is written in C, I have to use an API. That API is PyDAQFlex. The thermocouple reader also came with a tester script, written in C. I'm trying to get a temperature reading from the thermocouple reader, but it only outputs the CJC value.
My code:
import daqflex
d = daqflex.USB_2001_TC()
def get_temperature():
return float(d.send_message("?AI{0}:CJC/DEGC").encode("utf-8"))
The output of my code:
u'AI{0}:CJC/DEGC=23.8'
Note: 23.8 is not the temperature. That value is the CJC, as seen in the tester script's command line output below. It's related, but not the value I'm looking for.
The tester script's code:
http://pastebin.com/Atsdy7X0 (to get the temperature, I press "t" and then "k" because I have a K-type thermocouple).
The tester script's command line output:
http://pastebin.com/jq4Rr4QX (the temperature here is accurate. This is what I want to plug into my script.)
The PyDAQFlex script:
https://github.com/torfbolt/PyDAQFlex/blob/master/daqflex/devices.py (see line 105)
The C code for the thermocouple reader:
http://pastebin.com/rEDR9efR (Not included in entirety, only the relevant parts.)
I am seriously struggling to see my mistake here. This exact piece of code appears to have worked for someone else in the PyDAQFlex Github page, so I'm extremely confused. I have emailed the creator of the software, a person in Github with a similar issue as me, and I just spent 6 hours in various IRC chats. Please help me. If it helps, I used parts of this tutorial to install the drivers and things for the thermocouple reader. Thank you so much.
Source: (StackOverflow)
I have a program I wrote in C that starts mplayer with a pipe, I then control mplayer through that pipe. It seems that at times when I send a command over the pipe it crashes. The following are the relevant parts of my code and what I have done to debug it.
The original code:
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);
I ran into the problem that if mplayer finished, thus making it so
nothing is at the other end of the pipe and I still pipe over the stop
my program crashes. To solve this I changed it to the following:
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);
mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);
if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}
This fix worked great for me and it stop crashing.
Then I let other use the program and I starting getting
crashing every once in a while. As I could not get my
program to crash myself I change it to the following to see where
the program was crashing.
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
printf("command: mplayer -quiet -slave video.mkv > mplayer.log");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);
mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);
printf("mplayer_status: command: pidof -s mplayer. Got %s, value %d.",status_read_char,mplayer_pid);
if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
printf("command: stop.");
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}
The last thing I got before my program crashed the next time was:
mplayer_status: command: pidof -s mplayer. Got 27323, value 27323.
To me this indicates that it is crashing while piping over the stop
command to mplayer.
Does anyone know what is going wrong here? And any ideas on how to
prevent it from crashing?
Source: (StackOverflow)
I am adding values to the time (hours, minutes, seconds) members of my tm
struct and they are not updating/normalizing even though I'm using mktime()
Here is the code:
struct tm timeStruct;
char buffer[80];
timeStruct.tm_year = 2016 - 1900;
timeStruct.tm_mon = 3;
timeStruct.tm_mday = 32;
timeStruct.tm_hour = 23;
timeStruct.tm_min = 59;
timeStruct.tm_sec = 59;
timeStruct.tm_isdst = -1;
printf( "Date before adding interval: \n");
mktime(&timeStruct);
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);
printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );
/*
* Add intervals to time
*/
timeStruct.tm_sec += 2;
timeStruct.tm_min += 2;
timeStruct.tm_hour += 5;
printf( "Date after adding interval: \n");
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);
printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );
Console Output:1
This is a print out of the console output:
Date before adding interval:
Mon May 2 23:59:59 2016
the year is 116
the month is 4
the day is 2
the hours are 23
the minutes are 59
the seconds are 59
Date after adding interval:
Mon May 2 28:61:61 2016
the year is 116
the month is 4
the day is 2
the hours are 28
the minutes are 61
the seconds are 61
I am using Eclipse, compiling with Cygwin, on a Windows 7 machine.
Source: (StackOverflow)
Hanging on geeksforgeeks about bitfields, found this example:
#include <stdio.h>
struct test
{
unsigned int x;
long int y: 33;
unsigned int z;
};
int main()
{
struct test t;
unsigned int *ptr1 = &t.x;
unsigned int *ptr2 = &t.z;
printf("%d", ptr2 - ptr1);
return 0;
}
As result, output is 4. But why? x occupies 4 bytes, y - 8, and z - 4. Difference in addresses x and z must be 8?
Source: (StackOverflow)
I trying to use CSDP which is a mathematical library for SDP.
I download the library an extract the lib (libsdp.a). It is using lapack and blas lib, so I add -lblas and -llapack options.
I want to compile with cmake, hier is my CmakeList file (I comment a lot of line, I just want to test the compilation of example.c with is an example given by CSDP) :
# Cette commande non obligatoire est fortement conseillée.
cmake_minimum_required (VERSION 2.6)
# Déclaration du projet.
# Les fichiers CMakeLists pourront référer à la racine du projet par la variable
# ${ECMA_SOURCE_DIR} et ${ECMA_BINARY_DIR}
project(projet_ECMA)
set(EXE run)
# L'exécutable sera rangé différemment en fonction de la plateformee.
# Par défaut le binaire est construit dans le répertoire courant (?)
# set(EXECUTABLE_OUTPUT_PATH ../bin)
# set( EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE} )
# SET (CMAKE_C_COMPILER "/usr/bin/clang")
# SET (CMAKE_C_FLAGS "-Wall -std=c99")
# SET (CMAKE_C_FLAGS_DEBUG "-g++")
# SET (CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG")
# SET (CMAKE_C_FLAGS_RELEASE "-O4 -DNDEBUG")
# SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
#
# SET (CMAKE_CXX_COMPILER "/usr/bin/clang++")
# SET (CMAKE_CXX_FLAGS "-Wall")
# SET (CMAKE_CXX_FLAGS_DEBUG "-g")
# SET (CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG")
# SET (CMAKE_CXX_FLAGS_RELEASE "-O4 -DNDEBUG")
# SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
#
# SET (CMAKE_AR "/usr/bin/llvm-ar")
# SET (CMAKE_LINKER "/usr/bin/llvm-ld")
# SET (CMAKE_NM "/usr/bin/llvm-nm")
# SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
# SET (CMAKE_RANLIB "/usr/bin/llvm-ranlib")
#set(CSDP_DIR "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
#find_package(CSDP REQUIRED)
SET (BLAS "/usr/lib/libcblas.a")
SET (LAPACK "/usr/lib/liblapack.a")
SET (CSDP "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
# Les options de compilation
# add_definitions(-Wall -Wextra -ansi -O2 -Wwrite-strings
# -Wuninitialized -Wno-missing-braces
# -Wno-missing-field-initializers)
add_definitions(
# -Wno-unused-private-field # Pour inhiber un warning de cplex 12.4
# -m64
# -g
# -fPIC
# -fexceptions
# -pg
# -DNDEBUG
# -DIL_STD # Pour cplex en C++
# -std=c++11
# -o
-O3
# -pthread
#-L/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib
-ansi
-Wall
-DNOSHORTS
-DUSEGETTIME
# -lsdp
-lsdp -llapack
-latlas
-lcblas
-lgfortran
-lm
-lg2c
-lctmg -lf2c
)
# Config spécifique à un système
# - UNIX vrai sous une plateforme Unix (don macosx)
# - APPLE vrai pour un os apple (donc macosx !)
# - WIN32 : vrai sous Windows (32 et 64bit !)
if(APPLE)
message("=> Détection système Apple")
set(CMAKE_EXE_LINKER_FLAGS "-Wl,-no_compact_unwind")
endif()
# file(
# GLOB
# srcs
# src/*.cpp
# src/*.cc
# src/*.c
# src/*.hh
# src/*.h
# )
# On définit la liste des tous les fichiers sources (dont les includes)
# cmale se débrouillera pour trouver le main() et les dépendances.
# On peut préciser des sous-répertoires, des groupes de fichiers, ...
# Mais ATTENTION aux fichiers inutilisés : ils seront compiler et peuvent
# provoquer des erreurs. Il peut donc être référable de préciser exactement les
# fichiers sources
file(
GLOB
srcs
# src/site.*
# src/station.*
# src/remorque.*
# src/arc.*
# src/util.*
# src/logger.*
# src/options.*
# src/bench.*
# src/*Solver.*
# src/solver.*
# src/cir.*
# src/solu.*
# src/main.*
# src/*hpp
# /home/hassan/Bureau/ECMA/projet_ECMA/trunk/include/*.*
# src/*cpp
src/*.cc
src/*.hh
src/example.c
src/*.h
# src/*.*
)
# Le ou les exécutables à générer
add_executable(${EXE} ${srcs})
# Les répertoire ou chercher vos includes (ou ceux de cplex, ...)
include_directories(
# ${PROJECT_SOURCE_DIR}
# ${PROJECT_BINARY_DIR}
#$ENV{CONCERT_INCLUDE_DIR}
$ENV{CSDP_INCLUDE}
#$ENV{CPOPTIMIZER_INCLUDE_DIR}
#$ENV{CPLEX_INCLUDE_DIR}
# $ENV{LEMON_INCLUDE}
#$ENV{CPOPTIM_INCLUDE_DIR}
# $ENV{GLPK_INCLUDE}
)
# Ajouter ici les répertoires de vos bib. dynamiques utilisées
#
link_directories(
# ${PROJECT_BINARY_DIR}/lemon
# $ENV{LEMON_LIB}
# $ENV{GLPK_LIB}
$ENV{CSDP_LIB}
# $ENV{CONCERT_LIB_DIR}
# $ENV{CPLEX_LIB_DIR}
)
#find_library(CPLEX cplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(ILO_CPLEX ilocplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(CPOTIMIZER cpoptimizer HINTS $ENV{CPOPTIMIZER_LIB_DIR})
#find_library(CONCERT concert HINTS $ENV{CONCERT_LIB_DIR})
find_library(CSDP sdp HINTS $ENV{CSDP_LIB})
# Ajouter ici les bibliothèques dynamiques que vous utilisez
#
target_link_libraries(${EXE} blas) # pour programmation multithead
target_link_libraries(${EXE} lapack) # pour programmation multithead
#target_link_libraries(${EXE} sdp) # pour programmation multithead
target_link_libraries(${EXE} pthread) # pour programmation multithead
target_link_libraries(${EXE} m) # lib mathématique
target_link_libraries(${EXE} ${ILO_CPLEX}) # spécial cplex
target_link_libraries(${EXE} ${CPLEX}) # spécial cplex
target_link_libraries(${EXE} ${CPOPTIMIZER}) # spécial cplex
target_link_libraries(${EXE} ${CONCERT}) # spécial cplex
message("=> CSDP is ${CONCERT}")
#target_link_libraries(${EXE} ${BLAS}) # spécial csdp
#target_link_libraries(${EXE} ${LAPACK}) # spécial csdp
target_link_libraries(${EXE} ${CSDP}) # spécial csdp
#target_link_libraries(${EXE} ${BLAS}) # spécial csdp
# target_link_libraries(${EXE} emon) # lib de graphe
# target_link_libraries(${EXE} glpk) # solveur PLNE gratuit
# La liste des exécutables mono-fichiers à compiler
## set(demo_srcs
## main.cc
## test1.cc
## test2.cc
## )
# file(GLOB demo_srcs src/*.cc)
## foreach(demo_src ${demo_srcs})
## get_filename_component( demo_name ${demo_src} NAME_WE )
## message("=> demo_src=${demo_src}")
## message("=> demo_name=${demo_name}")
## add_executable(${demo_name} ${demo_src})
## target_link_libraries(${demo_name} emon)
## endforeach()
# Quelques messages précisant la configuration utilisée
#
message("=> CSDP_INCLUDE is $ENV{CSDP_INCLUDE}")
message("=> CSDP_LIB is $ENV{CSDP_LIB}")
message("=> ILOG_CPLEX_INCLUDE is $ENV{CPLEX_INCLUDE_DIR}")
message("=> ILOG_CPLEX_LIB is $ENV{CPLEX_LIB_DIR}")
message("=> ILOG_CONCERT_INCLUDE is $ENV{CONCERT_INCLUDE_DIR}")
message("=> ILOG_CONCERT_LIB is $ENV{CONCERT_LIB_DIR}")
# message("=> LEMON_INCLUDE is $ENV{LEMON_INCLUDE}")
# message("=> LEMON_LIB is $ENV{LEMON_LIB}")
# message("=> GLPK_INCLUDE is $ENV{GLPK_INCLUDE}")
# message("=> GLPK_LIB is $ENV{GLPK_LIB}")
message("=> srcs is ${srcs}")
# Ceci affiche 8 sur un machine 64 bits ou 4 sur un machine 32 bit
message("=> CMAKE_SIZEOF_VOID_P is ${CMAKE_SIZEOF_VOID_P}")
message("\n")
#
# Complément pour ajouter quelques cibles personnalisées dans le Makefile généré
#
EXECUTE_PROCESS(
COMMAND date +%Y%m%d-%Hh%M
OUTPUT_VARIABLE date_stamp
OUTPUT_STRIP_TRAILING_WHITESPACE
)
GET_FILENAME_COMPONENT( project_dir_name ${CMAKE_SOURCE_DIR} NAME )
# On peut compléter les cible du Makefile généré
# (la comande finale de cette ciblesera ajoutée à CMakeFiles/Makefile2)
# (puis Essayer de créer un cmake tbz !!)
ADD_CUSTOM_TARGET(distclean
COMMAND @echo Nettoyage complet des sources
COMMAND @echo \"Répertoire courant = `pwd`\"
COMMAND @echo "CMAKE_CURRENT_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}"
# COMMAND make clean
COMMAND find ${CMAKE_CURRENT_BINARY_DIR} -name "CMakeCache.txt" | xargs rm -rf
COMMAND rm -rf ${CMAKE_CURRENT_BINARY_DIR}/*
)
ADD_CUSTOM_TARGET(dc
COMMAND make distclean
)
ADD_CUSTOM_TARGET(cc
COMMAND make distclean
)
ADD_CUSTOM_TARGET(c
COMMAND make clean
)
# Attention : cette commande construit une cible pour le Makefile.
# Il faut protéger les double-quote si l'on veux qu'elles ne soient pas consommées
# par cmake mais passée au Makefile.
# Un seul COMMENT par cible semble-t-il
ADD_CUSTOM_TARGET(tbz
COMMENT "Création d'une archive datée du projet"
COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
# tar -C newDir : pour se placer dans le répertoire parent de l'archive
COMMAND tar cjf ${CMAKE_SOURCE_DIR}-${date_stamp}.tbz
-C ${CMAKE_SOURCE_DIR}/..
${project_dir_name}-${date_stamp}
COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
COMMAND @echo \" => Archive faite : ${project_dir_name}-${date_stamp}.tbz\"
)
ADD_CUSTOM_TARGET(txz
COMMENT "Création d'une archive datée du projet (TEST XZ)"
COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
# tar -C newDir : pour se placer dans le répertoire parent de l'archive
COMMAND tar cf ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
-C ${CMAKE_SOURCE_DIR}/..
${project_dir_name}-${date_stamp}
COMMAND xz ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
COMMAND mv ${CMAKE_SOURCE_DIR}-${date_stamp}.tar.xz ${CMAKE_SOURCE_DIR}-${date_stamp}.txz
COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
COMMAND @echo \" => Archive faite : ${project_dir_name}-${date_stamp}.tbz\"
)
# ADD_CUSTOM_TARGET(zip
# COMMENT "Création d'une archive datée du proje (TEST ZIP°t"
# COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
# COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
# COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
# COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
# COMMAND echo \"1: CMAKE_SOURCE_DIR-date_stamp==1==${CMAKE_SOURCE_DIR}-${date_stamp}\"
# COMMAND echo \"2: project_dir_name-date_stamp==2==${project_dir_name}-${date_stamp}\"
# # tar -C newDir : pour se placer dans le répertoire parent de l'archive
# # COMMAND '_pwd=`pwd`'
# # COMMAND pushd ${CMAKE_SOURCE_DIR}/..
# COMMAND echo 'pushd; zip -r -v -y -o -9 ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
# ${project_dir_name}-${date_stamp} ; popd'
# COMMAND sh -c "pushd; zip -r -v -y -o -9 ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
# ${project_dir_name}-${date_stamp} ; popd"
# # COMMAND zip -r -v -y -o -9 ${CMAKE_SOURCE_DIR}-${date_stamp}.zip
# # ${project_dir_name}-${date_stamp}
# COMMAND 'cd $_pwd'
# # COMMAND popd
# COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
# COMMAND @echo \" => Archive faite : ${project_dir_name}-${date_stamp}.tbz\"
# )
INCLUDE(InstallRequiredSystemLibraries)
IF(WIN32 AND NOT UNIX)
SET(CPACK_NSIS_MODIFY_PATH ON)
ENDIF(WIN32 AND NOT UNIX)
INCLUDE(CPack)
#./
The problem is, I think that libsdp.a need library (blas, lapack and math) but, even if I add it in my Cmake, he don't succeed to find it :
[100%] Building C object CMakeFiles/run.dir/src/example.c.o
/usr/bin/cc -DNOSHORTS -DUSEGETTIME -I/home/hassan/Bureau/ECMA/projet_ECMA/trunk/include -O3 -ansi -Wall -lsdp -llapack -latlas -lcblas -lgfortran -lm -lg2c -lctmg -lf2c -o CMakeFiles/run.dir/src/example.c.o -c /home/hassan/Bureau/ECMA/projet_ECMA/src/example.c
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c: In function ‘main’:
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c:62:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
printf("%d \n", sqrt(2));
^
Linking C executable run
/usr/bin/cmake -E cmake_link_script CMakeFiles/run.dir/link.txt --verbose=1
/usr/bin/cc CMakeFiles/run.dir/src/example.c.o -o run -rdynamic -lblas -llapack -lpthread -lm trunk/lib/libsdp.a
trunk/lib/libsdp.a(initsoln.o): dans la fonction « initsoln »:
initsoln.c:(.text+0x2a9): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x2ed): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x334): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm2 »:
norms.c:(.text+0x1d): référence indéfinie vers « dnrm2_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm1 »:
norms.c:(.text+0x4d): référence indéfinie vers « dasum_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norminf »:
norms.c:(.text+0x81): référence indéfinie vers « idamax_ »
trunk/lib/libsdp.a(sdp.o): dans la fonction « sdp »:
sdp.c:(.text+0x1ed7): référence indéfinie vers « dpotrf_ »
sdp.c:(.text+0x2104): référence indéfinie vers « pow »
sdp.c:(.text+0x7cf3): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8651): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88eb): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88f5): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8968): référence indéfinie vers « pow »
sdp.c:(.text+0x89bd): référence indéfinie vers « sqrt »
sdp.c:(.text+0x89e9): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(Fnorm.o): dans la fonction « Fnorm »:
Fnorm.c:(.text+0xcb): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(calc_dobj.o): dans la fonction « calc_dobj »:
calc_dobj.c:(.text+0x2d): référence indéfinie vers « ddot_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult »:
mat_mult.c:(.text+0xef): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult_raw »:
mat_mult.c:(.text+0x479): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(solvesys.o): dans la fonction « solvesys »:
solvesys.c:(.text+0x40): référence indéfinie vers « dpotrs_ »
trunk/lib/libsdp.a(linesearch.o): dans la fonction « linesearch »:
linesearch.c:(.text+0x39f): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x416): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x488): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x4ff): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0xe2b): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(matvec.o): dans la fonction « matvec »:
matvec.c:(.text+0xb8): référence indéfinie vers « dgemv_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_blk »:
chol.c:(.text+0x36): référence indéfinie vers « dpotrf_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_diag »:
chol.c:(.text+0x134): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol »:
chol.c:(.text+0x1bd): référence indéfinie vers « dpotrf_ »
chol.c:(.text+0x2e1): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_inv »:
chol.c:(.text+0x42f): référence indéfinie vers « dtrtri_ »
trunk/lib/libsdp.a(qreig.o): dans la fonction « qreig »:
qreig.c:(.text+0x539): référence indéfinie vers « sqrt »
qreig.c:(.text+0x64f): référence indéfinie vers « sqrt »
qreig.c:(.text+0x718): référence indéfinie vers « sqrt »
collect2: error: ld returned 1 exit status
make[2]: *** [run] Erreur 1
Source: (StackOverflow)
How can I implement a linked list for storing 10,20,30 .Please help me with a simple example.
Source: (StackOverflow)
We were given this code, and was supposed to modify it so that whenever a client connects to a server and sends a message the server should reply I hear you dude. That is working for one and multiple clients but next task was to when ever a new client connects the server should tell that to all the other clients that are connected.
I assumed this would be fairly easy but its not working out like I thought it would. Since the server always get sock 3 and first client gets 4 and second client gets 5 etc, I tried to make a for loop that messaged whenever a new client connects the loop will send message to 4,5 which just made the server close itself directly. I then tried to just make when ever a new client connects that the server should message the first client(4) which it actually does but only if client(4) writes a message to the server he recieves that broadcast that the server sent.
So it seems like the client wants to write but needs to write something before he recieves the broadcast from the server, any help would appreciated since we're kinda beginners with all this.
This is how the code looks like at the moment.
server.c
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <pthread.h>
#define PORT 5555
#define MAXMSG 512
void *connection_handler(void *socket_desc)
{
int sock = *(int*)socket_desc;
int read_size;
char *message, client_message[2000], *message_to_client;
message = "Greetings! I am your connection handler\n";
write(sock, message, strlen(message));
while( (read_size = recv(sock, client_message, 2000, 0)) > 0)
{
client_message[read_size] = '\0';
printf("Client[%d]: %s", sock, client_message);
message_to_client = "I hear you dude...";
write(sock, message_to_client, 19);
memset(client_message, 0, 2000);
}
if(read_size == 0)
{
printf("Client[%d] disconnected", sock);
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
free(socket_desc);
return 0;
}
int makeSocket(unsigned short int port) {
int sock;
struct sockaddr_in name;
/* Create a socket. */
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock < 0) {
perror("Could not create a socket\n");
exit(EXIT_FAILURE);
}
name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
perror("Could not bind a name to the socket\n");
exit(EXIT_FAILURE);
}
return(sock);
}
int main(int argc, char *argv[])
{
int sock;
int clientSocket;
int i;
int *new_sock;
char *broadcast;
fd_set activeFdSet, readFdSet;
struct sockaddr_in clientName;
socklen_t size;
sock = makeSocket(PORT);
if(listen(sock,1) < 0)
{
perror("Could not listen for connections\n");
exit(EXIT_FAILURE);
}
FD_ZERO(&activeFdSet);
FD_SET(sock, &activeFdSet);
while(1)
{
printf("Waiting for connections\n");
readFdSet = activeFdSet;
if(select(FD_SETSIZE, &readFdSet, NULL, NULL, NULL) < 0)
{
perror("Select failed\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < FD_SETSIZE; ++i)
{
if(FD_ISSET(i, &readFdSet))
{
if(i == sock)
{
size = sizeof(struct sockaddr_in);
pthread_t sniffer_thread;
while(( clientSocket = accept(sock, (struct sockaddr *)&clientName, (socklen_t *)&size)))
{
puts("Connection accepted");
new_sock = malloc(1);
*new_sock = clientSocket;
if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
broadcast = "NEW CLIENT CONNECTED";
write(4, broadcast, sizeof(broadcast)); //just to see if when ever a new client connects the first client should get all these messages
write(4, broadcast, sizeof(broadcast));
write(4, broadcast, sizeof(broadcast));
pthread_detach(sniffer_thread);
puts("Handler assigned");
FD_SET(*new_sock, &activeFdSet);
}
if(clientSocket < 0)
{
perror("Could not accept connection\n");
exit(EXIT_FAILURE);
}
}
else
{
if(readMessageFromClient(i) < 0)
{
close(i);
FD_CLR(i, &activeFdSet);
}
}
}
}
}
}
and for the client the code looks like this
client.c
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 5555
#define hostNameLength 50
#define messageLength 256
void initSocketAddress(struct sockaddr_in *name, char *hostName, unsigned short int port)
{
struct hostent *hostInfo;
name->sin_family = AF_INET;
name->sin_port = htons(port);
hostInfo = gethostbyname(hostName);
if(hostInfo == NULL)
{
fprintf(stderr, "initSocketAddress - Unknown host %s\n",hostName);
exit(EXIT_FAILURE);
}
name->sin_addr = *(struct in_addr *)hostInfo->h_addr;
}
void writeMessage(int fileDescriptor, char *message)
{
int nOfBytes;
nOfBytes = write(fileDescriptor, message, strlen(message) + 1);
if(nOfBytes < 0)
{
perror("writeMessage - Could not write data\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
int sock;
struct sockaddr_in serverName;
char hostName[hostNameLength];
char messageString[messageLength];
char buffer[1024];
if(argv[1] == NULL)
{
perror("Usage: client [host name]\n");
exit(EXIT_FAILURE);
}
else
{
strncpy(hostName, argv[1], hostNameLength);
hostName[hostNameLength - 1] = '\0';
}
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("Could not create a socket\n");
exit(EXIT_FAILURE);
}
initSocketAddress(&serverName, hostName, PORT);
if(connect(sock, (struct sockaddr *)&serverName, sizeof(serverName)) < 0)
{
perror("Could not connect to server\n");
exit(EXIT_FAILURE);
}
printf("\nType something and press [RETURN] to send it to the server.\n");
printf("Type 'quit' to nuke this program.\n");
fflush(stdin);
recv(sock, buffer, 1024, 0);
printf(buffer);
while(1)
{
printf("\n>");
fgets(messageString, messageLength, stdin);
messageString[messageLength - 1] = '\0';
if(strncmp(messageString, "quit\n",messageLength) != 0)
writeMessage(sock, messageString);
if(recv(sock, buffer, 1024, 0) > 0)
printf(buffer);
}
}
Source: (StackOverflow)
#include <iostream>
#include <sstream>
#include "blocknode.h"
using namespace std;
class MemoryManager
{
public:
MemoryManager(unsigned int memsize);
unsigned char * malloc(unsigned int request);
void free(unsigned char * blockptr);
blocknode *getFirstPtr();
friend ostream & operator<<(ostream & out,const MemoryManager &M);
private:
unsigned int memsize;
unsigned char *baseptr;
blocknode * firstBlock;
void mergeForward(blocknode *p);
void splitBlock(blocknode *p,unsigned int chunksize);
};
Here is the BLOCKNODE.h file
#include <iostream>
using namespace std;
struct blocknode
{
unsigned int bsize;
bool free;
unsigned char *bptr;
blocknode *next;
blocknode *prev;
blocknode(unsigned int sz,unsigned char *b,bool f=true,blocknode
*p=0,blocknode *n=0):
bsize(sz),free(f),bptr(b),prev(p),next(n) {}
};
CPP FILE
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include "MemoryManager.h"
using namespace std;
ostream & operator<<(ostream & out,const MemoryManager &M)
{
blocknode *tmp = M.firstBlock;
assert(tmp);
while(tmp)
{
out << "[" << tmp->bsize << ",";
if (tmp->free)
out << "free] ";
else
out << "allocated] ";
if (tmp->next)
out << " -> ";
tmp = tmp->next;
}
return out;
}
MemoryManager::MemoryManager(unsigned int memtotal): memsize(memtotal)
{
baseptr = new unsigned char[memsize];
firstBlock = new blocknode(memsize,baseptr);
}
blocknode *MemoryManager::getFirstPtr()
{
return firstBlock;
}
unsigned char * MemoryManager::malloc(unsigned int request)
// Finds the first block in the list whose size is >= request
// If the block's size is strictly greater than request
// the block is split, with the newly create block being free.
// It then changes the original block's free status to false
{
blocknode * tmp = this->firstBlock;
assert(tmp);
while (tmp){
if (tmp->bsize >= request){
if (tmp->bsize > request){
splitBlock(tmp, request);
return tmp->bptr;
}
tmp->free = false;
return tmp->bptr;
}
tmp = tmp->next;
}
}
void MemoryManager::splitBlock(blocknode *p, unsigned int chunksize)
// Utility function. Inserts a block after that represented by p
// changing p's blocksize to chunksize; the new successor node
// will have blocksize the original blocksize of p minus chunksize and
// will represent a free block.
// Preconditions: p represents a free block with block size > chunksize
// and the modified target of p will still be free.
{
if (p->free == false || p->bsize <= chunksize) {
cout << "Error splitting memory....exiting with error code 1" << endl;
exit(1);
}
blocknode * heap = new blocknode(p->bsize,p->bptr + chunksize,true,0,0);
heap->bsize = p->bsize - chunksize;
heap->prev = p;
p->bsize = chunksize;
p->next = heap;
}
void MemoryManager::mergeForward(blocknode *p)
// merges two consecutive free blocks
// using a pointer to the first blocknode;
// following blocknode is deleted
{
blocknode * tmp = p->next;
p->bsize += p->next->bsize;
p->next = tmp->next;
tmp->next->prev = p;
delete tmp;
}
void MemoryManager::free(unsigned char *blockptr)
// makes the block represented by the blocknode free
// and merges with successor, if it is free; also
// merges with the predecessor, it it is free
{
blocknode * tmp = this->firstBlock->next;
assert(tmp);
while (tmp) {
if (tmp->bptr == blockptr) {
tmp->free = true;
if (tmp->prev->free == true) {
mergeForward(tmp->prev);
}
if (tmp->next->free == true) {
mergeForward(tmp);
}
}
tmp = tmp->next;
}
}
The goal of this program is to pretty much simulate the C heap manager which deals with malloc() and free(). I am having trouble with the last four functions of the memory manager cpp file. (refer to the comments) The code compiles however my program crashes during runtime, it says that there is an unhanded exception at memory location XxXXXXXXX does anyone know what is causing this? Line 110 ("if(tmp->next->free == true)") is where the program breaks
Source: (StackOverflow)
This relatively simple program keeps on crashing my visual studio 2013, it doesn't give me an error message that i can tell you guys and from looking at my program I can't see any major flaws with it.
Visual studio tries to debug it and than crashes. Can someone tell me what is wrong with my program?
#include <stdio.h>
int main()
{
int a = 0, counter, total = 0;
printf("enter the number of terms you want to display\n");
scanf_s("%d", a);
for (counter = 0; counter <= a; counter++){
total = counter + total;
printf("%d + ", total);
}
printf("You have finished the program, press enter to exit"); /*Letting the user know that the program is finished*/
}
Source: (StackOverflow)
I'm working on a simple program that supposed to change a string to all uppercase or all lowercase depending on the arguments. For example, if the programs name is change:
./change -u thiswillbeuppercase
THISWILLBEUPPERCASE
./change -l THISWILLBELOWERCASE
thiswillbelowercase
The issue im having if that i cannot figure out how to perform the uppercase action by default, if no options are provided. For example, this is how i would like it to perform:
./change thiswillbeuppercase
THISWILLBEUPPERCASE
Here is what my main function looks like currently:
int main(int argc, char *argv[]) {
int c;
while((c = getopt(argc,argv,"u:s:l:")) != -1){
char *str = optarg;
if(c == '?'){
c = optopt;
printf("Illegal option %c\n",c);
} else{
switch(c){
case 'u':
strupper(str);
break;
case 'l':
strlower(str);
break;
case 's':
strswitch(str);
break;
default:
strupper(str);
break;
}
}
}
return 0;
}
I tried calling the strupper function in the default part of the switch statement but that doesn't seem to work. As of now the program does nothing when provided with no options.
I search stackoverflow for similar questions and i found someone with the same issue, but their question is related to bash and not C.
If anyone has any advice i would really appreciate it. Thank you.
Source: (StackOverflow)
I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:
1
5 1 2 0 2 2 5 8 4 3 6 6 2 5 5 7 2 1 1 2
7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.
As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character.
Now, this might seem silly, but what I have so far is this:
#include <stdio.h>
#include <ctype.h>
/*
int logBase10 (int num) {
method to calculate the log base 10 of num
}
*/
int main (int argc, char * argv[]) {
char alpha;
int count = 0;
int ascii[128] = {0};
while ( (alpha = getchar()) != EOF) {
count++;
ascii[(int)alpha]++;
alpha = getchar();
}
printf("Char \t Count \n");
printf("------------------------\n");
for (int i = 0; i < 127; i++) {
if(ascii[i] > 0) {
printf("%c \t %d \n", i, ascii[i]);
}
}
}
Which produces an output like this:
Char Count
------------------------
5
93
, 6
- 2
. 3
; 2
C 2
I 6
N 1
T 1
W 2
a 26
b 5
c 8
d 13
e 55
f 11
g 7
h 28
i 32
k 3
l 26
m 17
n 31
o 27
p 12
q 1
r 26
s 22
t 42
u 11
v 8
w 8
y 13
z 1
First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:
if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
printf("%c \t %d \n", i, ascii[i]);
}
to no avail. Trying that produced more gibberish characters instead.
Any help/feedback is appreciated.
Source: (StackOverflow)
I am trying to write a program that reads the stdin stream looking for words (consecutive alphabetic characters) and for each word rotates it left to the first vowel (e.g. "friend" rotates to "iendfr") and writes this sequence out in place of the original word. All other characters are written to stdout unchanged.
So far, I have managed to reverse the letters, but have been unable to do much more. Any suggestions?
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_STK_SIZE 256
char stk[MAX_STK_SIZE];
int tos = 0; // next available place to put char
void push(int c) {
if (tos >= MAX_STK_SIZE) return;
stk[tos++] = c;
}
void putStk() {
while (tos >= 0) {
putchar(stk[--tos]);
}
}
int main (int charc, char * argv[]) {
int c;
do {
c = getchar();
if (isalpha(c) && (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'o' || c == 'O' || c == 'u' || c == 'U')) {
push(c);
} else if (isalpha(c)) {
push(c);
} else {
putStk();
putchar(c);
}
} while (c != EOF);
}
-Soul
Source: (StackOverflow)
Making a basic shell and I need to handle file redirection. Specifically I am stumped on how I can feed data into a program like sort
for example from a file.
Something on the command line would look like this:
$ sort < test.txt
How do I accomplish this kind of functionality in my own mini shell made in C?
I thought that maybe sort
read from stdin
but I guess I can't really write the contents of a file to stdin
due to the read only aspect so I'm wondering how I actually get this data into something like sort
for example? I am currently using forks and then using execvp()
to execute programs.
Source: (StackOverflow)
I have failed to build a naive project using Visual Studio 2015.
It's a matter of environment which is still not fixed.
I am using Windows 10 Education, using Visual Studio Enterprise 2015.
Thank you so much for your help.
Error TRK0005 Failed to locate: "CL.exe". The system cannot find the file specified. myproj D:\Documents\XXX 1
Source: (StackOverflow)