我試圖讓在C程式,讀取文本檔案,并替換\r\n有\n相同的檔案轉換,從DOS到UNIX結束行。我使用fgetc該檔案并將其視為二進制檔案。提前致謝。
#include <stdio.h>
int main()
{
FILE *fptr = fopen("textfile.txt", "rb ");
if (fptr == NULL)
{
printf("erro ficheiro \n");
return 0;
}
while((ch = fgetc(fptr)) != EOF) {
if(ch == '\r') {
fprintf(fptr,"%c", '\n');
} else {
fprintf(fptr,"%c", ch);
}
}
fclose(fptr);
}
uj5u.com熱心網友回復:
如果我們假設檔案使用單位元組字符集,那么在將文本檔案從 DOS 轉換為 UNIX 時,我們只需要忽略所有的 '\r' 字符。
我們還假設檔案的大小小于最高的無符號整數。
我們做這些假設的原因是為了使示例簡短。
請注意,下面的示例會按照您的要求覆寫原始檔案。通常您不應該這樣做,因為如果發生錯誤,您可能會丟失原始檔案的內容。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
// Return a negative number on failure and 0 on success.
int main()
{
const char* filename = "textfile.txt";
// Get the file size. We assume the filesize is not bigger than UINT_MAX.
struct stat info;
if (stat(filename, &info) != 0)
return -1;
size_t filesize = (size_t)info.st_size;
// Allocate memory for reading the file
char* content = (char*)malloc(filesize);
if (content == NULL)
return -2;
// Open the file for reading
FILE* fptr = fopen(filename, "rb");
if (fptr == NULL)
return -3;
// Read the file and close it - we assume the filesize is not bigger than UINT_MAX.
size_t count = fread(content, filesize, 1, fptr);
fclose(fptr);
if (count != 1)
return -4;
// Remove all '\r' characters
size_t newsize = 0;
for (long i = 0; i < filesize; i) {
char ch = content[i];
if (ch != '\r') {
content[newsize] = ch;
newsize;
}
}
// Test if we found any
if (newsize != filesize) {
// Open the file for writing and truncate it.
FILE* fptr = fopen(filename, "wb");
if (fptr == NULL)
return -5;
// Write the new output to the file. Note that if an error occurs,
// then we will lose the original contents of the file.
if (newsize > 0)
count = fwrite(content, newsize, 1, fptr);
fclose(fptr);
if (newsize > 0 && count != 1)
return -6;
}
// For a console application, we don't need to free the memory allocated
// with malloc(), but normally we should free it.
// Success
return 0;
} // main()
只洗掉 '\r' 后跟 '\n' 用這個回圈替換回圈:
// Remove all '\r' characters followed by a '\n' character
size_t newsize = 0;
for (long i = 0; i < filesize; i) {
char ch = content[i];
char ch2 = (i < filesize - 1) ? content[i 1] : 0;
if (ch == '\r' && ch2 == '\n') {
ch = '\n';
i;
}
content[newsize ] = ch;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360990.html
