|
The task is to replace - looks for all occurrences of string from and replaces it with string to.
It is possible to specify one or more files on which to perform the replace
operation(s) in a single replace command.
and this is my code:
void replace(char* OldWord, char* NewWord)
{
char *result = NULL;
char buff[1000];
char c;
char line[1000];
FILE * f = fopen ("file1.txt", "r+");
int count=0;
while (fgets(buff, sizeof(buff), f))
{
result = replaceWord(buff, OldWord, NewWord);
//
}
//
//free(result);
}
char *replaceWord(const char *s, const char *oldW,const char *newW)
{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
static int k=0;
k++;
char newline[1000];
FILE * fp;
// printf("%s\n",oldW);
//printf("%s\n",newW);
// Counting the number of times old word
// occur in the string
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;
while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
fp = fopen ("file1.txt", "w");
rewind(fp);
fseek(fp,i-newWlen,SEEK_SET);
fprintf(fp,"%s\n",result);
}
else
{
result[i++] = *s++;
}
}
result[i] = '\0';
fp = fopen ("file1.txt", "w");
fprintf(fp,"%s\n",result);
// printf("%d\n",k);
return result;
}
the replace function does not give the desired output
The command line looks like:
./a.out replace old_word new_word files.txt
must replace old_word with the new_word in all files.
|
|
|
|
|
Member 12957547 wrote: It is possible to specify one or more files on which to perform the replace
operation(s) in a single replace command.
Why "in a single replace command"?
Why not just open your files in the loop and perform the replacement in each file? 
|
|
|
|
|
because I do not know how many items get from the CLI
|
|
|
|
|
Member 12957547 wrote: because I do not know how many items get from the CLI |
Yes, you do, or at least main() does.
int main(int argc, char **argv)
argc is the number of arguments passed to main, and argv is an array of strings containing the command line arguments. Remeber that argv[0] is the program name, so argc is always > 0.
The following will print all the command line arguments
#include <stdio>
int main(int argc, char **argv)
{
for(int i = 0; i < argc; ++i)
printf("argv[%d] = \"%s\"\n", i, argv[i];
return0;
}
|
|
|
|
|
Haven't tried to run your code, but I do notice a couple things:
1: you call fopen() several times, but there's no corresponding fclose() . If you had a large file (say the text of the bible), and wanted to replace, "god" with "jimmy", you would probably run out of file handles before completing the task.
2: you continually call fopen on the same file. fopen("file1.txt", "w") truncates the file, so some future read may return EOF unexpectedly. [NB not necessarily the next read, as the call to fgets might fill an input buffer, which following calls use, rather than continually reading from the file] My suggestion would be to open a temporary file and write your output there, then copy or replace the input file with the temp file. tmpfile() might be useful, here.
3: fgets() reads up to size-1 bytes from the input stream. What happens if you have very long lines (over 999 chars, in your case), and the word you want occupies chars 996-1003? You'll get the first 3 chars in one read and the remaining 4 in the next, missing an occurrence. Might I suggest you look at getline() .
4: do you need to concern yourself with word case? Do you need to replace "babble" with "brook", "Babble" with "Brook" and "BABBLE" with "BROOK"?
|
|
|
|
|
Member 12957547 wrote:
the replace function does not give the desired output If that is the case, I'd take a step back and get it working before worrying about files. Just send the function a string of characters, and the find/replace terms. After that, then rope the file contents back in.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
A couple of things I've noticed:
1. You are always using 'file1.txt' in your code, not the filename(s) passed as argument
2. As has been pointed out, lines can be longer than 1000 chars.
3. You never close the file you've opened. That will cause changes in one file buffer to overwrite previous changes once the files are closed (or at the end of the program).
4. You only check for one occurence of a word per line. What if there are multiple occurrences?
Suggestions:
- As already pointed out, start with your replace functions and make sure they work as intended, before dealing with files!
- Make sure you always close the files you've opened
- Write the modified text into another, temporary file. Later erase the original file, and rename the temporary one. That way you can just keep on reading/writing without needing to close/open the file over and over again.
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
|
|
|
|
|
Hope it is OK to make new post.
I am still working on this assumption:
other
An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.
Adding full path to desired library to be added to existing library resolved the
"cannot find " issue.
Now the gcc++ needs to be told to actually link, contrary to the "other" instruction taken from Linux documentation.
I get same error when using libbluetooth.a.
'MODULE/M_TEST/CTEST.o' '-o' 'MODULE/M_TEST/CTEST.o' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
Finished building: ../MODULE/M_TEST/CTEST.cpp
g++: warning: /usr/lib/x86_64-linux-gnu/bluetooth: linker input file unused because linking not done
Building file: ../MODULE/M_SOCKET/CSOCKETCOMMON.cpp
Invoking: GCC C++ Compiler
|
|
|
|
|
You need to show us the command you are using to do the build. The message above suggests that you are only invoking the compile of some source module(s), so no library is needed.
|
|
|
|
|
Some very odd things here:
Vaclav_ wrote: 'MODULE/M_TEST/CTEST.o' '-o' 'MODULE/M_TEST/CTEST.o' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
That looks wrong. That looks like your compiler command could be boiled down to
g++ CTEST.o -o CTEST.o You're passing in and producing the same .o file, not creating an executable, only an intermediate object. In which case the g++ warning makes sense, since its telling you that the lib wasn't used to create the .o file. In which case you should be getting a g++ fatal error input file is same as output file.
Second thing is the warning itself. The path given is /usr/lib/x86_64-linux-gnu/bluetooth. Normally that would be libbluetooth.a. In which case the linker should be able to pick it up as -lbluetooth, since its in the expected location. It just doesn't have a name format that the linker recognizes as a library. I'd say say something messed up when installing the library, if this is indeed the case and you've not just messed up copying the output from your system to the forum.
|
|
|
|
|
As already noted by k5054, you (-o option) are asking the g++ to NOT perform the linking step.
Nevermind.
(thanks to k5054)
modified 28-Jan-20 15:54pm.
|
|
|
|
|
Oops, Ha Ha, actually, we both got that wrong. The compiler is quite happy to link an executable into a file named foo.o e.g.
$ g++ hello.cpp -o hello.o
$ ./hello.o
Hello World!
$
Its the -c option that compiles but does not link, so that must have been included in the command sent to the compiler.
|
|
|
|
|
Yes, of course you are right. Thank you for pointing out.
|
|
|
|
|
Stand-by.
I build some more test apps and "discovered" that type .so library has STANDARD IDE options for linker , but type .a , which I have been messing with, does NOT.
Also neither one of them show -l option, only -L.
Basically - forget IDE, back to GCC raw options.
|
|
|
|
|
Vaclav_ wrote: type .so library has STANDARD IDE options for linker , but type .a , which I have been messing with, does NOT. That makes no sense, there are no such things as standard IDE options for compiling and/or linking. The options are determined by the specific compiler and linker in use. You may have an IDE that is set up to use the most common options for gcc, but you still need to modify it depending whether you are trying to create a static archive (.a), or shared object library (.so).
|
|
|
|
|
Post-mortem FYI
SOLVED(?)
1.Both projects ( IDE terminology) works as expected.
NOT REALLY SURE WHY.
2.The “mother” executable - project has -lbluetooth -lRPI_BT_LIB, but ONLY
-L "${workspace_loc:/RPI_BT_LIB/Debug}" optioned.
3. There are NO references / options to “bluetooth” in RPI_BT_LIB, only source includes.
3. Adding “bluetooth” as per this ( no -l or -L !)
other
An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.
Creates “cannot find ...” error
4. Adding “/usr/…/bluetooth” creates “ did not link ...” error but has no effect on processing.
(It was pointed out that GCC was not optioned to link )
5. running “make clear” idefinites full library file name - “libRPI_RT_LIB.a”
6. Using “standard IDE” ( I am calling IDE UI form "standard" ) to build type .a library gives NO linking options, however building .so gives ALL options.
7. Using “standard IDE form” to build a project – executable or library – creates “system” default includes.
NOT sure if they are used only for source or linking libraries.
As far as I can tell this whole mess was because I could not tell if I was using
wrong GCC options
or
wrong syntax
It was NEVER about (-l / -L ).
The unanswered question remains - how does the RPI_BT_LIB library manages to use "bluetooth" library.
|
|
|
|
|
Vaclav_ wrote: how does the RPI_BT_LIB library manages to use "bluetooth" library. The same way that any code uses any library. Define the external references and add the library to the build process. Take a look at gcc library - Google Search[^] for more detailed information.
|
|
|
|
|
I am posting this here because I hope the actual output will help to solve the issue , and it is not small!
I have an app using bluetooth - linked to library "bluetooth". It works fine.
I need to identify the actual type of library ( Linux .a or .so ).
GCC options do not require prefix, such as "lib." or suffix - .a or .so thus GCC output cannot tell me the library file full name.
I also need the (-L) path to the library and GCC does not correlate -L with -l.
Help will be appreciated.
PS Please ignore the "undefined.." error.
Here is the actual GCC linker output
make all
Building target: RPI_BT_SERVER
Invoking: GCC C++ Linker
g++ -L/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_COMMON/src/MODULES/M_SOCKET_COMMON -L"/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_LIB/Debug" -v -o "RPI_BT_SERVER" ./src/MODULES/M_FILE_CLASS/CFILECLASS.o ./src/RPI_BT_SERVER.o -lbluetooth -lRPI_BT_LIB
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.12)
COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/
LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-L/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_COMMON/src/MODULES/M_SOCKET_COMMON' '-L/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_LIB/Debug' '-v' '-o' 'RPI_BT_SERVER' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
/usr/lib/gcc/x86_64-linux-gnu/5/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/5/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper -plugin-opt=-fresolution=/tmp/ccoEji8m.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -z relro -o RPI_BT_SERVER /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o -L/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_COMMON/src/MODULES/M_SOCKET_COMMON -L/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_LIB/Debug -L/usr/lib/gcc/x86_64-linux-gnu/5 -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.. ./src/MODULES/M_FILE_CLASS/CFILECLASS.o ./src/RPI_BT_SERVER.o -lbluetooth -lRPI_BT_LIB -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/5/crtend.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o
/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_LIB/Debug/libRPI_BT_LIB.a(CSOCKETCOMMON.o): In function `std::C_SOCKET_COMMON::SelectDevice(int)':
/media/z/DEV_COPY_LABEL/ECLIPSE_FOLDER/2019-12/Eclipse_2019_12/eclipse/Workspace_2019_12/RPI_BT_LIB/Debug/../MODULE/M_SOCKET/CSOCKETCOMMON.cpp:144: undefined reference to `str2ba'
|
|
|
|
|
Knowing "why" helps to motivate people; otherwise, it sounds like "make work". Seems like knowing what OS you're running under would be more useful.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
OK, isn’t all of that info in posted output ?
|
|
|
|
|
Just check the directory where this library is installed and you will see which type it is.
|
|
|
|
|
try ldd myprog . If the library shows up in the output, then it is dynamically linked, e.g. a .so library. If it doesn't, then its a static library (.a ).
Usually the linker (ld, not gcc), will prefer the dynamic library over the static, so the resulting executable will a) use new versions of the library, if it gets updated, and b) (less important these days) have a smaller on-disk footprint. If you are linking to the .so and you want to force the linker to use the static library you can do that with the following options to gcc
-Wl,-Bstatic -lsome_lib -Wl,-Bdynamic
If you don't add the -Wl,-Bdynamic at the end, then libc gets statically linked in, too, which is probably not what you want. Of course you could just pass -static to gcc for the final linking stage, and that will produced a static binary (no shared libs), which should run on most linux boxes of with the same architecture (e.g X86 or ARM). I say most, because if you compiled on say Ubuntu 18.04, and tried to run on something ancient, like maybe RedHat 9 (shrike), you would probably get a execution error.
But it would be helpful to know why you want to know this. Normally, we don't care whether we're linking to a dynamic or static library, just as long as the program works. Your question suggests to me that you're bumping up against an issue and are trying to force the OS into doing what you think it should, rather than working with the OS
|
|
|
|
|
The library works, was build few years back and I do not remember how I did it.
Reason for all this is that I need to implement same library in another project , therefore I need to identify the type and location. Hence "reverse engineering".
|
|
|
|
|
pick it in the makefile
ifeq (,$(wildcard somelibpath/sonelibrary.a))
endif
ifeq (,$(wildcard somelibpath/sonelibrary.so))
endif
You can even pick it out of a list of filenames in the makefile .. that is after all what the makefile is there for
In vino veritas
|
|
|
|
|
|