我需要讀取一個文本檔案(E3-5.txt),并搜索要被 c2 替換的字符 c1。這是我不完整的代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "r ");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
for(c = getc(fp); c != EOF; c = getc(fp))
{
if(c == 'm')
{
i = ftell(fp);
printf("\nPosition %d", i);
}
}
}
我在如何定位文本中 c1 的位置以及如何重寫它時遇到了麻煩。編輯:我使用了答案中的代碼,但它沒有更改文本。這是新代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "rb ");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
else
{
for(c = getc(fp); c != EOF; c = fgetc(fp))
{
if(c == c1)
{
fseek(fp, -1, SEEK_CUR);
fputc(c2, fp);
}
else
{
return 0;
}
}
}
return 0;
}
程式回傳 0 沒有在文本中寫入任何內容
uj5u.com熱心網友回復:
在這里你有一個非常幼稚的:
int freplace(FILE *f, char needle, char repl)
{
int result = 1;
int c;
if(f)
{
while((c = fgetc(f)) != EOF)
{
if(c == needle)
{
fseek(f, -1, SEEK_CUR);
fputc(repl, f);
//all I/O functions require error handling
}
}
}
return result;
}
uj5u.com熱心網友回復:
getc()回傳一個int所以你需要宣告int c不char c檢查 EOF。
ftell()獲取位置。使用fwrite()或fputc()通過設定寫入該位置的檔案fseek()。
轉至https://en.cppreference.com/w/c以供參考。許多初學者無法閱讀所有標準庫函式,有些甚至重新發明輪子。
uj5u.com熱心網友回復:
您真的不想直接操作檔案。曾經。這樣做只是要求資料損壞。相反,創建一個新檔案并在完成后移動它。此外,撰寫代碼要容易得多。你可以這樣做:
#include <stdio.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
int c1 = argc > 1 ? argv[1][0] : 'm';
int c2 = argc > 2 ? argv[2][0] : 'a';
const char *path = argc > 3 ? argv[3] : "stdin";
FILE *in = argc > 3 ? fopen(path, "r") : stdin;
if( in == NULL ){
perror(path);
return 1;
}
FILE *out = stdout;
char tmp[1024] = ".tmpXXXXX";
char *outpath = "stdout";
if( argc > 3 ){
outpath = tmp;
int fd = mkstemp(tmp);
if( fd == -1 ){
perror("mkstemp");
return 1;
}
if( (out = fdopen(fd, "w")) == NULL ){
perror(tmp);
return 1;
}
}
int c;
while( (c = fgetc(in)) != EOF ){
if( c == c1 ){
c = c2;
}
if( fputc(c, out) == EOF ){
perror(outpath);
return 1;
}
}
if( argc > 3 ){
if( fclose(out) ){
perror(outpath);
return 1;
}
if( rename(outpath, path) ){
perror(path);
return 1;
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/375394.html
