Problems with eval function skipping newlines in $(eval echo $myvar) - bash

I am currently working on a script meant to add a new project generation for any basic editor.
I am using the following structure in order to generate the right basic program (hello, world) according to the language selected by the user :
#!/bin/sh
#this is a short example in the case the user selected C as the language
TXTMAIN="\$TXTMAIN_C"
$TXTMAIN_C="#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
printf(\"hello, world\n\");
return EXIT_SUCCESS;
}"
MAIN="./main.c"
touch MAIN
echo -n "$(eval echo $TXTMAIN)" >> "$MAIN"
gedit MAIN
This piece of code gives the following output when you edit main.c :
#include <stdlib.h> #include <stdio.h> int main(int argc, char const* argv[]) { printf("hello, world\n"); return EXIT_SUCCESS; }
However, when replacing line 13 by echo -n "$TXTMAIN_C" >> "$MAIN", it gives the right output :
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
printf("hello, world\n");
return EXIT_SUCCESS;
}
I still don't know wether that's an echo or eval issue, or if there is a way around for my pointer-like problem.
Any advice is very welcome !

There are a few errors in your script, and it's more complicated than it should be.
If you want to use an indirect variable like that, use the ${!FOO} syntax, and put quotes where appropriate:
#!/bin/sh
#this is a short example in the case the user selected C as the language
TXTMAIN=TXTMAIN_C # don't force a $ here
TXTMAIN_C="#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
printf(\"hello, world\n\");
return EXIT_SUCCESS;
}"
MAIN="./main.c"
echo "${!TXTMAIN}" > "$MAIN" # overwrite here, if you want to
# append, use >>. `touch` is useless

Related

Xcode does not support printf_s ?

Not sure why Xcode complains "Use of undeclared identifier 'printf_s' did you mean 'printf'? Try to find help from Xcode manual but not useful.
#include <iostream>
#include <stdio.h>
int main(int argc, const char * argv[]) {
printf_s("Line one\n\t\tLine two\n");
return 0;
}

gcc using unlink and readdir, 7 days old files needs to be deleted

Using this code fetched from google.
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct dirent *entry;
DIR *dp;
chdir("/mnt/shared");
dp = opendir(".");
while( (entry = readdir(dp)) != NULL ) {
if ( strcmp(entry->d_name, ".") &&strcmp(entry->d_name, "..") ){
unlink(entry->d_name);
}
}
}`
In this could it be possible to delete files older than 7 days from the current date?
In perl i tried as follows, but wondering this could be achived with your help?
my $now = time();
my $DATEAGE = 60*60*24*7;
for my $file (#file_list) {
my #stats = stat($file);
if ($now-$stats[9] > $DATEAGE) {
print "$file\n";}
Build the full string of the file and use several syscalls(2) (notably stat(2)) ; read Advanced Linux Programming
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct dirent *entry;
DIR *dp;
time_t weekago;
time(&weekago);
weekago -= 86400*7;
dp = opendir("/mnt/shared");
if (!dp) { perror("/mnt/shared"); exit(EXIT_FAILURE); };
while( (entry = readdir(dp)) != NULL ) {
if ( strcmp(entry->d_name, ".")
&& strcmp(entry->d_name, "..") ){
char buf[256];
if (snprintf(buf, sizeof(buf),
"/mnt/shared/%s", entry->d_name)
>=sizeof(buf))
{ fprintf(stderr, "too long path %s\n", buf);
exit(EXIT_FAILURE);
};
struct stat st;
if (stat(buf,&st)) {
perror(buf);
exit(EXIT_FAILURE);
};
if ((st.st_mode & S_IFMT) == S_IFREG // a plain file
&& (st.st_mtime < weekago))
{
if (remove(buf)) perror(buf);
}
}
}
My untested code above is imperfect (and not very well indented): it don't handle file paths wider than 255. But you could improve it, e.g. using asprintf(3) to build the path in heap (then you'll need to free it).
Practically speaking, use find(1). If you need to recurse in a file tree in C, use nftw(3)

"struct has no member named" error with gcc on dev machine

#include <stdio.h>
#include <stdlib.h>
#include "ReadMethods.h"
int main(int argc,char * argv[])
{
DPDA WordChecker;
DPDA * WordCheckerPointer=&WordChecker;
WordChecker.DPDAFilename=(char*)malloc(25*sizeof(char));
WordChecker.DPDAInputFilename=(char*)malloc(25*sizeof(char));
WordChecker.DPDAOutputFilename=(char*)malloc(25*sizeof(char));
strcpy( WordChecker.DPDAFilename,argv[1]);
strcpy( WordChecker.DPDAInputFilename,argv[2]);
strcpy( WordChecker.DPDAOutputFilename,argv[3]);
readDPDA(argv[1],WordCheckerPointer);
readInputLines(argv[2],WordCheckerPointer,argv[3]);
return 0;
}
This is my code that gives error from mallocs until last strcpy() ,total 6 lines.The error is "DPDA has no member named DPDAFilename" and same for other fields for every malloc and strcpy linesthat i work on.Here is the part of header file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tagRule{
char *startingState;
char symbolToPop;
char expectedInput;
char *endingState;
char symbolToPush;
}Rule;
typedef struct tagStackDPDA{
char * arrayOfSymbols;
int stackElementCount;
char * currentState;
}stackDPDA;
typedef struct tagDPDA{
char * alphabet;
char * stackSymbols;
char ** states;
char *startingState;
char **finalStates;
int finalStatesAmount;
Rule * ruleList;
stackDPDA stackOfDPDA;
int sizeArray[4];//This array holds amount values of states,alphabet symbols,stack symbols and transition rules
char *DPDAFilename;
char *DPDAInputFilename;
char *DPDAOutputFilename;
}DPDA;
The code works fine in codeblocks environment but in gcc (-Wall -ansi).Those filenames come from input text files yet i am not sure it can cause this error.
Edit:By the way I am using this command line to compile;
gcc -Wall -ansi main.c ReadMethods.h -o WordChecker
May be if you compile in C mode, you have to use C-style comments in header?
/**/ instead of //

Xcode, Instruments, Allocations, Command Line App, not registering free()

I have a very simple Command Line Tool in Xcode:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(int argc, const char * argv[])
{
void *p = calloc(32, 1);
assert(p);
free(p);
return 0;
}
When I run Instruments->Allocations it shows one living block. The free seems to be ignored.
In the olden days, I remember that you could actually still use the last free'ed block. So I tried this:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(int argc, const char * argv[])
{
void *p = calloc(32, 1);
assert(p);
free(p);
void *q = calloc(32, 1);
assert(q);
free(q);
return 0;
}
Now, Instruments->Allocations shows no living blocks. This seems correct.
Can anyone explain or reproduce the problem I am seeing in the first program?
I'm using Xcode 4.1.1
Thanks.
Let me rephrase the comments above.
Apple LLVM in Xcode 5 resolved the alloc / free behavior so that no blocks allocated now, thus the free() method runs as expected.

Using strcmp to compare argv item with string literal isn't working as I was expecting

I'm quite new to Visual C++ so this might be a 'schoolboy' error, but the following code is not executing as I'd expected:
#include "stdafx.h"
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
if (strcmp((char*)argv[1], "--help") == 0)
{
printf("This is the help message."); //Won't execute
}
return 0;
}
The executable, named Test.exe is launched as follows
Test.exe --help
I was expecting the message This is the help message. but I'm not seeing it - debugging reveals that the if condition comes out as -1 and not 0 as I'd expect. What am I doing wrong?
OK, I've figured out what's going on. The argv[] array is declared as TCHAR*, which is a macro that adjust the type based on whether or not Unicode has been enabled for the project (wchat_t if it is or char if it is not). The strcmp function, which I was trying to use, is the non-Unicode string comparison while wcscmp is the Unicode equivalent. The _tcscmp function uses the appropriate string comparison function depending on the Unicode setting. If I replace strcmp with _tcscmp, problem solved!
#include "stdafx.h"
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
if (_tcscmp(argv[1], _T("--help")) == 0)
{
printf("This is the help message."); //Will execute :)
}
return 0;
}
The _T function converts the argument to Unicode, if Unicode is enabled.
See also: Is it advisable to use strcmp or _tcscmp for comparing strings in Unicode versions?

Resources