can you tell me what adjustments i can do for my code, or any simplifications? What shouldn't
i repeat, what should i change ? This code converts every word to upper case, if you find some problems,pls write in order to fix it))
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
FILE * fPtr, *fPtr1;
int c; /*to store characters*/
char filename[20];
char filename2[20] = "temp.txt";
printf("Enter name of file: ");
scanf("%19s%*c",filename);
fPtr = fopen(filename, "r");
fPtr1 = fopen(filename2, "w");
c = fgetc(fPtr);
while(c!=EOF){
if(c!='\n'){
if(islower(c)){
fputc(c-32,fPtr1);
}else{
fputc(c,fPtr1);
}
}else{
fputc(c,fPtr1);
}
c = fgetc(fPtr);
}
fclose(fPtr);
fclose(fPtr1);
remove(filename);
rename(filename2,filename);
fPtr = fopen(filename, "r");
c = fgetc(fPtr);
while(c!=EOF){
printf("%c",c);
c = fgetc(fPtr);
}
fclose(fPtr);
}
This program does what you say it does. But I recommend some changes that your future self will appreciate.
First, always initialize your variables; this habit will help to prevent odd bugs in your future code. Set ints to a value out of your expected range (e.g. maybe -1 in this case); set pointers to NULL; set char arrays to { '\0' } or to "\0".
Next, check your file pointers (fPtr, fPtr1) for NULL after fopen.
Finally, specific to this code, your check for new-line is unnecessary; islower will return 0 if the parameter is not a lowercase alphabetic character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
char *mygets(char *s, size_t sz) {
int ch;
size_t i = 0;
while((ch = getchar()) != '\n' && i < sz)
s[i++] = ch;
s[i] = '\0';
return s;
}
int main(void) {
FILE *fPtr;
char filename[MAX+1];
int c, i;
printf("Enter name of file: ");
mygets(filename, MAX+1);
if(!strstr(filename, ".txt"))
strcat(filename, ".txt");
if((fPtr = fopen(filename, "r+")) == NULL) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
i = 0;
while((c = fgetc(fPtr)) != EOF) {
fseek(fPtr, i, SEEK_SET);
fputc(toupper(c), fPtr);
i++;
}
rewind(fPtr);
while((c = fgetc(fPtr)) != EOF)
putchar(c);
fclose(fPtr);
return 0;
}
Related
I have written a small program to read in a series of strings from a file and then to store them in a 2D Arrray. The strings are read into the array correctly, yet my program is not countering the number of rows in the file like I had expected.
I am honestly at a loss and cannot figure out why the program is not counting the rows in the file. Any explanation as to what I am doing wrong is greatly appreciated.
Here is the code that I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp;
char nameArray[20][120], str[20];
int i = 0, j = 0, n;
int count = 0;
char name[20]; //filename
int ch;
printf("Please enter a file name: ");
scanf("%s", &name);
fp = fopen(name, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!\n", name);
return -1;
}
while (fscanf(fp, "%s", str) != EOF)
{
strcpy(nameArray[i], str);
i++;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
count++;
}
for (i = 0; i<=count; i++)
{
printf("%s", nameArray[i]);
}
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int process_stream(FILE *fpntr);
char *fgetline(FILE *fpntr);
int main(int argc, char* argv[]) {
FILE *fpntr;
char filename[100], c;
int a = 0;
printf("Please enter a file name/directory: \n");
scanf("%s", filename);
fpntr = fopen(filename, "r");
if (fpntr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
c = fgetc(fpntr);
while (c != EOF){
printf ("%c", c);
c = fgetc(fpntr);
if (c == '\n')
{
a++;
printf("%d", a);
}}
fclose(fpntr);
return 0;
exit (0);
}
Firstly, implement just as what you says.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE *fptr;
char filename[100];
int c;
int lineNumber = 1;
printf("Please enter a file name/directory: \n");
scanf("%99s", filename);
// Open the file
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
// While ((c = read a character) is not EOF)
while ((c = fgetc(fptr)) != EOF){
// If (c is \n)
if (c == '\n') {
// Print "lineNumber", then increment it
printf("%d. ", lineNumber);
lineNumber++;
}
// Print c
printf ("%c", c);
// End while
}
// Close the file
fclose(fptr);
return 0;
}
Unfortunately, this code won't work well and its output is
#include <stdio.h>1.
#include <stdlib.h>2.
int hoge;3.
int fuga;4.
when the input file is
#include <stdio.h>
#include <stdlib.h>
int hoge;
int fuga;
The fault is that you are printing line numbers at the end of lines.
They should be at the beginning of lines.
I would use a flag that indicates beginning of lines.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE *fptr;
char filename[100];
int c;
int lineNumber = 1;
int isBeginningOfLine = 1;
printf("Please enter a file name/directory: \n");
scanf("%99s", filename);
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("cannot open file \n");
exit(0);
}
//read contents from file
while ((c = fgetc(fptr)) != EOF){
if (isBeginningOfLine) {
print("%d. ", lineNumber);
isBeginningOfLine = 0;
}
if (c == '\n') {
lineNumber++;
isBeginningOfLine = 1;
}
printf ("%c", c);
}
fclose(fptr);
return 0;
}
Now I get
1. #include <stdio.h>
2. #include <stdlib.h>
3. int hoge;
4. int fuga;
I am using CodeBlocks on Windows to compile.
Why the program gives me this answer? Why there are so much as and don't get the answer 123456abcdef?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
char s[100] = "abcdef";
char c1 = '0';
int i = 0;
fp = fopen("ot.txt", "w");
if (fp == NULL) {
printf("file open error");
exit(0);
}
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
while (c1 != EOF) {
c1 = fgetc(fp);
putchar(c1);
}
fclose(fp);
}
There are multiple problems in your code:
c1 should be defined with type int to accommodate for all values returned by fgetc(). a char cannot unambiguously store EOF.
You should open the file in write+update mode "w+"
You should rewind the stream pointer before reading back from it for 2 reasons: a seek operation is required between read and write operations and you want to read the characters from the start of the file.
You need to test for EOF after reading a byte with fgetc(), otherwise you will output the EOF converted to unsigned char to stdout before exiting the loop.
It is good style to return 0; from main() to indicate success and non-zero to indicate failure.
Here is a corrected version:
#include <stdio.h>
int main(void) {
FILE *fp;
char s[] = "abcdef";
int i, c;
fp = fopen("ot.txt", "w+");
if (fp == NULL) {
printf("file open error\n");
return 1;
}
i = 0;
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
rewind(fp);
while ((c1 = fgetc(fp)) != EOF) {
putchar(c1);
}
printf("\n");
fclose(fp);
return 0;
}
What i need to do, is to take a file of n lines, and for every x lines, create a new file with the lines of the original file. An example would be this:
Original File:
stefano
angela
giuseppe
lucrezia
In this case, if x == 2, 3 file would be created, in order:
First file:
stefano
angela
Second FIle:
giuseppe
lucrezia
Third File:
lorenzo
What i've done so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * filename = malloc(sizeof(char)*64);
char * ext = ".txt";
char number[2];
for(int i = ix; i < *mem; i++)
{
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && (ix*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
I'm stack with segmentation error, i couldn't find the bug doing
gdb myprogram
run
bt
I really appreciate any help.
EDIT:
I've changed some things and now it works, but it creates an additional file that contains strange characters. I need to still adjust some things:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * ext = ".txt";
for(int i = ix; i < *mem; i++)
{
char * filename = malloc(sizeof(char)*64);
char * number = malloc(sizeof(char)*64);
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
free(number);
free(filename);
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && ((ix-1)*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
There are a few problems in your code. But first I think you need to fix the most important thing
int step = lines/N;
Here step is 0 if your input file has less than N lines of text. This is because lines and N both are integer and integer division is rounding down.
I won't fix your code, but I'll help you with it. Some changes I
suggest:
Instead of getlines, use getline(3) from the standard
library.
fseek(fp, 0 , SEEK_SET) is pointless.
In char * filename = malloc(sizeof(char)*64), note that
both arguments to malloc are constant, and the size is arbitrary.
These days, it's safe to allocate filename buffers statically,
either on the stack or with static: char filename[PATH_MAX].
You'll want to use limits.h to get that constant.
Similarly you have no need to dynamically allocate your FILE
pointers.
Instead of
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
use sprintf(filename, "temp%d%s", i+1, ext)
get familiar with err(3) and friends, for your own convenience.
Finally, your recursive Split is -- how shall we say it? -- a nightmare. Your whole program
should be something like:
open input
while getline input
if nlines % N == 0
create output filename with 1 + n/N
open output
write output
nlines++
I tried to change all random lowercase letters to uppercase letters in this program.First of all, I have initialized in lowercase.txt AkfsASlkALfdk.Then I read from it and changing all the lowercase letters into capital ones.The problem is,when I opened the capital.txt is ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌAKFSASLKALFDK.Where did the error come from?I couldn't find it yet and I decided to ask you.
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <conio.h>
int main()
{
int i;
char s[100];
char k[100];
FILE *kp;
kp = fopen("lowercase.txt", "r");
if (kp == NULL)
{
printf("Error in opening file.\n");
system("pause");
exit(1);
}
FILE *temp;
temp = fopen("capital.txt", "w");
if (kp == NULL)
{
printf("Error in opening file.\n");
system("pause");
exit(2);
}
printf("Opening file is successful.\n");
if (fscanf(kp, "%s", &s) != EOF)
{
for (i = 0; i < 100; i++)
{
if (s[i] >= 97 && s[i] <= 122)
{
s[i] -= 32;
}
}
}
fprintf(temp, "%s", k);
getch();
return 0;
}
Multiple issues in your code which together cause the issues
You are storing the opened FILE* in temp, but checking kp. I think that is because you copy pasted the check from above. Can be easily fixed by changing the variable
You perform the capitalization operation outside what was set by scanf. As suggested by #MOehm, change the loop condition to s[i]
Finally you are converting the string in place in s but are saving k in the file. k is never modified. Change fprintf(temp, "%s", k); to fprintf(temp, "%s", s);
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *append(const char *s, char c) {
int len = strlen(s);
char buf[len+2];
strcpy(buf, s);
buf[len] = c;
buf[len + 1] = 0;
return strdup(buf);
}
int main(int argc, char **argv)
{
char ch;
FILE *fp;
if (argc != 2)
return (0);
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
char *res;
while((ch = fgetc(fp)) != EOF)
{
res = append(res, ch);
}
fclose(fp);
int i = 0;
while (i < strlen(res))
{
if (res[i] >= 97 && res[i] <= 122)
res[i] = res[i] - 32;
i++;
}
printf("%s\n", res);
return 0;
}
here is a quick example
read the file char by char and add each char in a char *. Then for each character lowercase char, sub 32 to get the uppercase char and write it then print. Give the filename as first parameter when you start the programm