Is it possible to manipulation a file in memory where we can operate on the text just as we do with regular file; then save it to disk under a new file name without destroying the original file?
Weeks ago, I found two examples that gave me a glimmer of hope, but I still have not touch first base where one would need to open a real file on disk when using these two examples.
Nonetheless to get to it I tried many ways to squeeze in the isspace() function for simplicity. In the fork-code, it just is added no matter what I alter, and in the malloc-code it over write the first half of the original file in memory. My head is spinning and feet’s are drowning.
Any help would be appreciated.
Thank you
FORK:
Code:
#include <ctype.h>
#include <unistd.h>
#include <stdio.h>
char c;
int i=0;
char str[]="A B C\n";
int main(){
int p[2]; pipe(p); FILE *f = fdopen( p[1], "w" );
if( !fork() ){
fprintf( f, "working" );
return 0;
}
fclose(f); close(p[1]);
char buff[100]; int len;
while( (len=read(p[0], buff, 100))>0 )
printf(" from child: '%*s'", len, buff );
puts("");
// PART 2
//
while (str[i])
{
c=str[i];
if (isspace(c)) c='\n';
putchar (c);
i++;
}
}
MALLOC:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
char c;
int i=0;
char str[]="A B C\n";
int i;
int written = 0;
int main(int argc, char **argv)
{
FILE *f = fopen("/dev/null", "w");
char *buf = malloc(100);
setbuffer(f, buf, 100);
for (i = 0; i < 10; i++)
{
written += fprintf(f, "Number %d\n", i);
}
for (i = 0; i < written; i++) {
printf("%c", buf[i]);
// PART 2
//
while (str[i]){
c=str[i];
if (isspace(c)) c=' ';
putchar (c);
i++;
}
}
}