W
William Payne
Hello, I need to write a program that opens a text file and scans the entire
file for a specific line and when that line is found, a particular word on
that line is to be replaced. The new word is given as an argument to the
program. I wrote a small test program that doesn't work because strcmp()
fails to find a matching line. Here's the code:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
FILE* in_file = NULL;
FILE* out_file = NULL;
char* temporary_file_name = NULL;
char line[128];
if(argc < 2)
{
fprintf(stderr, "You must supply a word.\n");
return 1;
}
in_file = fopen("test.txt", "r");
if(in_file == NULL)
{
fprintf(stderr, "Error opening test.txt\n");
return 1;
}
temporary_file_name = tmpnam(NULL);
out_file = fopen(temporary_file_name, "w");
while(fgets(line, sizeof(line), in_file))
{
printf("Line read: %s\n", line);
if(strcmp(line, "set imap_user=root") == 0)
{
printf("Replacing.\n");
strcpy(line, "set imap_user=");
strcat(line, argv[1]);
}
fputs(line, out_file);
}
fclose(in_file);
fflush(out_file);
fclose(out_file);
remove("test.txt");
rename(temporary_file_name, "test.txt");
return 0;
}
And here's the original file test.txt:
set spoolfile=imap://sysinst.ida.liu.se/INBOX
set folder=imap://sysinst.ida.liu.se/INBOX
set imap_user=root
set ssl_starttls=no
set sendmail="/usr/sbin/sendmail -oem -oi"
Why doesn't it work?
/ William Payne
file for a specific line and when that line is found, a particular word on
that line is to be replaced. The new word is given as an argument to the
program. I wrote a small test program that doesn't work because strcmp()
fails to find a matching line. Here's the code:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
FILE* in_file = NULL;
FILE* out_file = NULL;
char* temporary_file_name = NULL;
char line[128];
if(argc < 2)
{
fprintf(stderr, "You must supply a word.\n");
return 1;
}
in_file = fopen("test.txt", "r");
if(in_file == NULL)
{
fprintf(stderr, "Error opening test.txt\n");
return 1;
}
temporary_file_name = tmpnam(NULL);
out_file = fopen(temporary_file_name, "w");
while(fgets(line, sizeof(line), in_file))
{
printf("Line read: %s\n", line);
if(strcmp(line, "set imap_user=root") == 0)
{
printf("Replacing.\n");
strcpy(line, "set imap_user=");
strcat(line, argv[1]);
}
fputs(line, out_file);
}
fclose(in_file);
fflush(out_file);
fclose(out_file);
remove("test.txt");
rename(temporary_file_name, "test.txt");
return 0;
}
And here's the original file test.txt:
set spoolfile=imap://sysinst.ida.liu.se/INBOX
set folder=imap://sysinst.ida.liu.se/INBOX
set imap_user=root
set ssl_starttls=no
set sendmail="/usr/sbin/sendmail -oem -oi"
Why doesn't it work?
/ William Payne