I found this program on the internet so I decided to try it, it converts a file to another type of file. I compiled and ran on my MAC OS X 10.9.1 through terminal, but it gave me a segmentation fault 11. What can I do to fix this?
#include <stdio.h>
#define SRAM_SIZE (32 * 1024)
typedef FILE* pfile;
static unsigned char SRAM[SRAM_SIZE];
int main(void)
{
pfile in, out;
register int i;
in = fopen("input.sra", "rb");
for (i = 0; i < SRAM_SIZE; i++)
SRAM[i ^ ~0&3] = fgetc(in);
fclose(in);
out = fopen("output.sra", "wb");
for (i = 0; i < SRAM_SIZE; i++)
fputc(SRAM[i], out);
fclose(out);
return 0;
}
You have no error checking. Change:
in = fopen("input.sra", "rb");
for (i = 0; i < SRAM_SIZE; i++)
SRAM[i ^ ~0&3] = fgetc(in);
fclose(in);
...
to:
in = fopen("input.sra", "rb");
if (in == NULL)
{
printf("Unable to open 'input.sra'.\n");
return -1;
}
for (i = 0; i < SRAM_SIZE; i++)
SRAM[i ^ ~0&3] = fgetc(in);
fclose(in);
...
You should do the same for the output file too. There are a lot of ways this can fail and just blindly accessing an untested value is bad practice.
Related
I am a beginner in programming and I need to find out palindromes in the first file and put them into the second one.
I have a Thread 1: EXC_BAD_ACCESS (code=1, address=0x68), when I am trying to start the code
#include <stdio.h>
#include <string.h>
int main ()
{
char line[255];
unsigned long k;
int i;
int flag = 1;
FILE *file = fopen("1zad.txt", "r");
FILE *new = fopen("new1.txt", "a");
while(!feof(file) && !ferror(file))
{
fgets(line, 255, file);
k = strlen(line);
for (i = 0;i < k/2;i++)
{
if(line[i]!=line[k-1-i]){
flag = 0;
}
}
if(flag == 1){
fputs(line, new);
}
}
fclose(file);
fclose(new);
return 0;
}
it underlines "!feof", text files are available and near the program file.
i have no ideas what is going wrong
I need some help with my C project:
I need to write a c program who receives 2 parameters:
1) The name of a text file(infile) which is in the same catalog
2) A number k>0
And creates 2 new files,outfile1 & outfile 2 as:
Outfile 1: k,2*k,3*k…. character of infile
Outfile 2: k,2*k,3*k…..line of infile
Example:
INFILE
Abcdefg
123456
XXXXXX
01010101
OUTFILE 1:
Cf25XX101
OUTFILE 2:
XXXXXX
I wrote some code ,but its not working. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** read_lines(FILE* txt, int* count) {
char** array = NULL;
int i;
char line[100];
int line_count;
int line_length;
*count = 0;
line_count = 0;
while (fgets(line, sizeof(line), txt) != NULL) {
line_count++;
}
rewind(txt);
array = malloc(line_count * sizeof(char *));
if (array == NULL) {
return NULL;
}
for (i = 0; i < line_count; i++) {
fgets(line, sizeof(line), txt);
line_length = strlen(line);
line[line_length - 1] = '\0';
line_length--;
array[i] = malloc(line_length + 1);
strcpy(array[i], line);
}
*count = line_count;
return array;
}
int main(int argc, char * argv[]) {
char** array = NULL;
FILE* file = NULL;
const char* filename = NULL;
int i;
int line_count;
int k;
char c;
printf("ENTER ONE PHYSICAL NUMBER\n");
do{
if(k>0)
scanf("%d",&k);
else{
printf("ENTER ONE PHYSICAL NUMBER\n");
scanf("%d",&k);
}
}while(k<=0);
file = fopen("LEIT.txt", "rt");
if (file == NULL) {
printf("CANT OPEN FILE %s.\n", filename);
return 1;
}
array = read_lines(file, &line_count);
printf("ARRAY:\n");
for (i = 0; i < line_count; i++) {
printf("[%d]: %s\n", (i+1), array[i]);
}
printf("CALCULATING OUTFILE1 AND OUTFILE2\n");
printf("OUTFILE1:\n");
for(i=0;i<line_count;i++){
c=i*k;
printf("%c\n",array[c]);
}
printf("WRITING OUTFILE1 COMPLETE!\n");
printf("OUTFILE2:\n");
for(i=0;i<line_count;i++){
c=i*k;
printf("%c\n",array[c]);
}
printf("WRITING OUTFILE2 COMPLETE!\n");
return 0;
}
My actual problem is calculate and write into files (outfile1 and outfile2) the result...
You need to close file after finishing reading/writing it with fclose.
You can create and write strings to a file using fopen with correct mode.
You can output formatted string to a file by using fprintf.
It seems that you don't want to print the 0th character/line, so in the last for loop, i should start from 1 (or start from 0 but add 1 later).
array[c] is a string, not a character. So when printing it, you should use %s specifier instead of %c.
It is not a good idea using char as count in later for loops unless you know input file will be very short. signed char can only count to 127 before overflow (unsigned char can count to 255). But if you have a very long file, for example thousands of lines, this program would not work properly.
array is malloced in function char** read_lines(FILE* txt, int* count). After finish using it, you need to dealloc, or free it by calling
for (i = 0; i < line_count; i++) {
free(array[i]);
}
and followed by free(array). This avoids memory leakage.
Modified code is here. In the following code, char c is not used. This is the part where you process output files, and before return 0; in main function.
printf("CALCULATING OUTFILE1 AND OUTFILE2\n");
printf("OUTFILE1:\n");
// Since we finished using LEIT.txt, close it here.
fclose(file);
// Mode: "w" - Write file. "+" - Create if not exist.
// You can lso use "a+" (append file) here if previous record need to be preserved.
FILE *out1 = fopen("OUTFILE1.txt", "w+");
FILE *out2 = fopen("OUTFILE2.txt", "w+");
if ((out1 == NULL) || (out2 == NULL)) {
printf("CANT CREATE OUTPUT FILES.\n");
return 1;
}
// Out file 1.
unsigned int count = k;
for (i = 0; i < line_count; i++){
while (count < strlen(array[i])) {
// This just prints to stdout, but is good for debug.
printf("%c", array[i][count]);
// Write to the file.
fprintf(out1, "%c", array[i][count]);
// Calculate c for next char.
count += k + 1;
}
// Before go to next line, minus string length of current line.
count -= strlen(array[i]);
}
printf("\n");
printf("WRITING OUTFILE1 COMPLETE!\n");
// Close file.
fclose(out1);
// Out file 2.
printf("OUTFILE2:\n");
for (i = 1;i < line_count / k; i++){
count = i * k;
// This just prints to stdout, but is good for debug.
printf("%s\n", array[count]);
// Write to the file.
fprintf(out2, "%s\n", array[count]);
}
printf("WRITING OUTFILE2 COMPLETE!\n");
//Close file.
fclose(out2);
// dealloc malloced memory.
for (i = 0; i < line_count; i++) {
free(array[i]);
}
free(array);
I am writing a UNIX paste clone. However I keep getting "encountered a breakpoint" messages, but VS won't tell me on what line it happened.
#include <stdio.h>
#include <stdlib.h>
#define INITALLOC 16
#define STEP 8
int main(int argc, char *argv[])
{
if (horzmerge(argc - 1, argv + 1) == 0) {
perror("horzmerge");
return EXIT_FAILURE;
}
getchar();
return EXIT_SUCCESS;
}
int horzmerge(int nfiles, const char **filenames)
{
FILE **files;
char *line;
int i;
if ((files = malloc(nfiles * sizeof (FILE *))) == NULL)
return 0;
for (i = 0; i < nfiles; ++i)
if ((files[i] = fopen(filenames[i], "r")) == NULL)
return 0;
do {
for (i = 0; i < nfiles; ++i) {
if (getline(files[i], &line) == 0)
return 0;
fprintf(stdout, "%s", line);
free(line);
}
putchar('\n');
} while (!feof(files[0])); /* we can still get another line */
for (i = 0; i < nfiles; ++i)
fclose(files[i]);
free(files);
return 1;
}
int getline(FILE *fp, char **dynline)
{
size_t nalloced = INITALLOC;
int c, i;
if ((*dynline = calloc(INITALLOC, sizeof(char))) == NULL)
return 0;
for (i = 0; (c = getc(fp)) != EOF && c != '\n'; ++i) {
if (i == nalloced)
if ((*dynline = realloc(*dynline, nalloced += STEP)) == NULL)
return 0;
(*dynline)[i] = c;
}
(*dynline)[i] = '\0';
if (c == EOF)
return EOF;
return i;
}
I placed breakpoints, and saw that it was the free(line) statement in horzmerge. But sometimes the program runs fine. Sometimes it doesn't. Sometimes I get a "Heap corrupted" in getline. I've been working on this code for a week, still can't find the bug(s).
It looks to me like the line where you null-terminate the input string is capable of overrunning the buffer you calloced or realloced. That has the potential of corrupting your heap when you free that buffer.
Dont't forget to leave room for the null character at the end of the string when you allocate memory.
Null-terminated strings are like disco. They still suck forty years later.
I've written a program to mess around with writing pointers into files(fwrite) and reading into pointers from files(fread). However the program doesn't seem to write a single thing into the file, nor does it seem to read anything from the file; it just prints the final incrementation of my pointer 5 times and exits. Can anyone spot the error/mistake in my syntax that seems to be doing this?
#include <stdio.h>
int main() {
FILE *fTest;
int *testPtr;
int x = 10;
if ((fTest = fopen("test.c", "wb")) == NULL) {
printf("Error!");
}
testPtr = &x;
int i;
for (i = 0; i < 5; i++) {
fwrite(testPtr, sizeof(int), 1, fTest);
*testPtr += 1;
}
for (i = 0; i < 5; i++) {
fread(testPtr, sizeof(int), 1, fTest);
printf("%d", *testPtr);
}
fclose(fTest);
}
Steps to take:
Write the data to the file.
Close the file.
Open the file again in read mode.
Read the data from the file.
That should work.
Also, the output file name, test.c, seems a bit strange. Is that on purpose?
#include <stdio.h>
int main() {
FILE *fTest;
int *testPtr;
int x = 10;
char const* file = "test.data"; // Using .data instead of .c
testPtr = &x;
int i;
// Write the data.
if ((fTest = fopen(file, "wb")) == NULL) {
printf("Error!");
}
for (i = 0; i < 5; i++) {
fwrite(testPtr, sizeof(int), 1, fTest);
*testPtr += 1;
}
fclose(fTest);
// Read the data.
if ((fTest = fopen(file, "rb")) == NULL) {
printf("Error!");
}
for (i = 0; i < 5; i++) {
fread(testPtr, sizeof(int), 1, fTest);
printf("%d", *testPtr);
}
fclose(fTest);
}
Left aside the fact that you don't check thre return value of fwrite() I would assume that you do write into "test.c", after you run the program the file should exist with a size of 5 * sizeof(int) bytes. But you can't read from it for two reasons:
you open the file write-only. Change "wb" to "w+b" to allow reading
after writing, you must reset the read-write pointer to the beginning of the file: call fseek(fTest, 0, SEEK_SET ); before reading
The problem is that you're reading from the file while it's opened in write mode.
Add this code between your write loop and read loop and it will work:
fclose(fTest);
if ((fTest = fopen("test.c", "rb")) == NULL) {
printf("Error!");
}
I've been trying to blow the cobwebs off my C programming skills, and I've been getting an error I can't seem to figure out. This program reads in a list of integers separated by newlines. This bit happens in read_integer_file... I have no issues going through the input there. It's when I pass the data back to main via out that I have the problem.
#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int* out)
{
FILE* file;
file = fopen(filename, "r");
/* check if the file open was successful */
if(file == NULL)
{
return 0;
}
int num_lines = 0;
/* first check how many lines there are in the file */
while(!feof(file))
{
fscanf(file, "%i\n");
num_lines++;
}
/* seek to the beginning of the file*/
rewind(file);
out = malloc(sizeof(int)*num_lines);
if(out == NULL)
return 0;
int inp = 0;
int i = 0;
while(!feof(file))
{
fscanf(file, "%i\n", &inp);
out[i] = inp;
printf("%i\n", out[i]); /* <---- Prints fine here! */
i++;
}
return num_lines;
}
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("Not enough arguments!");
return -1;
}
/* get the input filename from the command line */
char* array_filename = argv[1];
int* numbers = NULL;
int number_count = read_integer_file(array_filename, numbers);
for(int i = 0; i < number_count; i++)
{
/* Segfault HERE */
printf("%i\n", numbers[i]);
}
}
You have not allocated any memory for numbers. Currently it is pointing to no where. When it gets back to the calling function it is still pointed to nowhere. Pass a pointer to a pointer to the function to allocate it within the function.
int read_integer_file(char* filename, int** out)
{
...
*out = malloc(sizeof(int)*num_lines);
...
int number_count = read_integer_file(array_filename, &numbers);
This is a version of your code working.. Keep in mind also that fscanf just skip the \n the way you wrote it so it's like writing fscanf(file, "%d");
And if you don't put a variable to handle what it reads the compiler may not see it but you'll probably get an error..
So here is the code :
#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int **out)
{
FILE* file;
file = fopen(filename, "r");
/* check if the file open was successful */
if(file == NULL)
{
return 0;
}
int num_lines = 0;
int garbi;
char garbc;
/* first check how many lines there are in the file */
while(!feof(file))
{
fscanf(file, "%d", &garbi);
fscanf(file, "%c", &garbc);
if (garbc=='\n') ++num_lines;
}
/* seek to the beginning of the file*/
rewind(file);
int *nbr = malloc(sizeof(int)*num_lines);
if(nbr == NULL)
return 0;
int i = 0;
while(!feof(file))
{
fscanf(file, "%d", &nbr[i++]);
fscanf(file, "%c", &garbc);
}
*out=nbr;
return num_lines;
}
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("Not enough arguments!");
return -1;
}
/* get the input filename from the command line */
char* array_filename = argv[1];
int *numbers = NULL;
int number_count = read_integer_file(array_filename, &numbers);
int i;
for(i = 0; i < number_count; ++i)
printf("%d\n", numbers[i]);
return 0;
}